我的SQL访问代码中的错误 [英] A bug in my SQL access code
问题描述
我正在编写将sql数据库与前端应用程序连接的代码(.net框架中的设计)
代码如下-----
I was writing the codes to connect sql database with frontend application(design in .net framework)
the codes were as follows-----
private void comboBox1_TextChanged(object sender, EventArgs e)
{
SqlCommand comm = new SqlCommand("Select log_name from dbo.niraj_table where log_id=''"+Convert.ToInt32(comboBox1.Text)+"''", conn);
SqlDataReader dr = comm.ExecuteReader();
textBox1.Text =Convert.ToString( dr["log_name"]);//This line gives me error_____conn is sqlconnection object here
}
代码调试器中显示的错误消息如下:
当没有数据存在时无法读取..
The error message shown in code debugger is as follows:
Unable to read when no data is present..
推荐答案
我猜这是因为您尚未调用SqlDataReader的Read()
方法而导致的错误SqlDataReader
到下一条记录.
添加以下代码行:
I guess the error is because you haven''t called the SqlDataReader''sRead()
method which advances theSqlDataReader
to the next record.
Add these lines of code:
if (dr.HasRows)
{
dr.Read();
textBox1.Text =Convert.ToString( dr["log_name"]);
dr.Close();
}
此外,在此行中:
Also, in this line:
SqlCommand comm = new SqlCommand("Select log_name from dbo.niraj_table where log_id='"+Convert.ToInt32(comboBox1.Text)+"'", conn);
您正在将log_id转换为整数,但通过将其用单引号("...")
来作为字符串字段传递
检查数据库中log_id的数据类型.如果是整数,请删除单引号.
希望这对您有帮助!
You are converting the log_id to integer but passing it as a string field by enclosing it in single quotes (''...'')
Check the datatype of log_id in the database. If it''s integer, remove the single quotes.
Hope this helps!
正确检查您的代码我认为您需要查看SqlCommand并将它的第一个参数作为字符串,但这是问题所在
Check your code properly i think you need to see the SqlCommand and it takes 1st argument as string but here is the problem
SqlCommand comm = new SqlCommand("Select log_name from dbo.niraj_table where log_id='"+Convert.ToInt32(comboBox1.Text)+"'", conn);//Error is here
但是您正在连接不正确的int,并且如果您只想检索一个值,则此解决方案会更好地工作
but you are concatenating int which is not correct and this solution would work better if you want to retrieve only one value
SqlDataReader dr = comm.ExecuteScalar();
然后这个
and then this
if (dr.HasRows)
{
dr.Read();
textBox1.Text =Convert.ToString( dr["log_name"]);
dr.Close();
}
这篇关于我的SQL访问代码中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!