从数据库中读取数据以显示在标签中 [英] reading data from database to display in label

查看:102
本文介绍了从数据库中读取数据以显示在标签中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何显示数据库中的余额.我已经尝试了以下代码,但运气不好.

how would i display the balance from my database. I have tried the following code but i am having no luck getting it to work.

SqlDataReader readdata;
          
                sqlCommandCheckBalance.Connection.Open();
                sqlCommandCheckBalance.CommandText = "SELECT * FROM Accounts WHERE accountID = '" + "accountID" + "'";  
                readdata = sqlCommandCheckBalance.ExecuteReader();
                string balanceDB = null;
                while (readdata.Read())
                {
                    balanceDB = readdata["balance"].ToString();
                }
                balanceShow.Text += " " + balanceDB.ToString();

推荐答案

删除备用双引号:
Take off the spare double quotes:
sqlCommandCheckBalance.CommandText = "SELECT * FROM Accounts WHERE accountID = '" + "accountID" + "'";

成为

sqlCommandCheckBalance.CommandText = "SELECT * FROM Accounts WHERE accountID = '" + accountID + "'";

或者(最好)使用参数化查询!


像这样吗? sqlCommandCheckBalance.Parameters ["accountID"].Value = balanceShow.Text;

还有

此行代码-readdata = sqlCommandCheckBalance.ExecuteReader();
无法将参数从字符串转换为int32 ...我如何将其转换为尝试一些操作但无济于事



这就是SQL抱怨传递的参数值-大概是帐户ID.
检查声明时指定的类型,或尝试以下操作:

Or (preferably) use a parametrized query instead!


like this? sqlCommandCheckBalance.Parameters["accountID"].Value = balanceShow.Text;

And

on this line of code - readdata = sqlCommandCheckBalance.ExecuteReader();
cannot convert parameter from string to int32... how would i convert it try a few things but nothing working



That is SQL complaining about the value of a parameter you have passed over - presumably the account ID.
Check the type you gave it when you declared it, or try this:

sqlCommandCheckBalance.CommandText = "SELECT * FROM Accounts WHERE accountID = @ID";
sqlCommandCheckBalance.Parameters.AddWithValue("@ID", accountID);

我不知道t保证可以编译,因为我不知道类型sqlCommandCheckBalance是-如果它是SqlCommand对象,应该没问题.
顺便说一句:您是否意识到可以在SqlCommand构造函数中同时指定命令和连接?

I don''t guarantee that will compile, because I don''t know type sqlCommandCheckBalance is - if it is an SqlCommand object it should be fine.
BTW: You do realise you can specify both the command and connection in the SqlCommand constructor?

SqlCommand sqlCommandCheckBalance = new SqlCommand("SELECT * FROM Accounts WHERE accountID = @ID", con);
sqlCommandCheckBalance.Parameters.AddWithValue("@ID", accountID);



很多人认为这是很多更整齐的方法!



A lot of people think it is a lot tidier way to do it!


这篇关于从数据库中读取数据以显示在标签中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆