如何修复ExecuteReader错误
本文关键字:错误 ExecuteReader 何修复 | 更新日期: 2023-09-27 18:05:55
Error异常类型为" System.Data.SqlClient. sql "。在System.Data.dll中发生了SqlException',但未在用户代码中处理。如何解决这个问题?图片:https://i.stack.imgur.com/7Sibc.png
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(@"Data Source=QEAG1YU4664IBKF'HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7");
conn.Open();
SqlCommand sc = new SqlCommand("select Title from TongHopDB", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Title", typeof(string));
dt.Load(reader);
cboxDB.ValueMember = "Title";
cboxDB.DisplayMember = "Title";
cboxDB.DataSource = dt;
conn.Close();
}
private void cboxDB_SelectedIndexChanged(object sender, EventArgs e)
{
string sql = "Select Title, Post from TongHopDB where Title = " + cboxDB.SelectedValue.ToString(); // câu query có thể khác với kiểu dữ liệu trong database của bạn
SqlConnection conn = new SqlConnection(@"Data Source=QEAG1YU4664IBKF'HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7");
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader sdr = cmd.ExecuteReader();
textBox1.Text = sdr.GetValue(0).ToString();
textBox2.Text = sdr.GetValue(1).ToString();
sdr.Close();
sdr.Dispose();
conn.Close();
conn.Dispose();
}
string sql = "Select Title, Post from TongHopDB where Title = '" + cboxDB.SelectedValue.ToString()+"'";
但是我强烈建议使用参数:
string sql = "Select Title, Post from TongHopDB where Title = @Title";
cmd.Paramaters.Add( "@Title",cboxDB.SelectedValue.ToString());
我强烈怀疑你的Title
是字符类型的,这就是为什么它需要用单引号作为;
where Title = '" + cboxDB.SelectedValue.ToString() + "'";
但不要这样用。
您应该始终使用参数化查询。这种字符串连接容易受到SQL注入攻击。
还可以使用using
语句自动处理SqlConnection
, SqlCommand
和SqlDataReader
对象,而不是手动调用Close
或Dispose
方法。
using(var conn = new SqlConnection(@"Data Source=QEAG1YU4664IBKF'HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7"))
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = "Select Title, Post from TongHopDB where Title = @title";
cmd.Parameters.Add("@title", SqlDbType.NVarChar).Value = cboxDB.SelectedValue.ToString();
// I assumed your column type is nvarchar.
conn.Open();
using(SqlDataReader sdr = cmd.ExecuteReader())
{
if(dr.Read())
{
textBox1.Text = sdr.GetValue(0).ToString();
textBox2.Text = sdr.GetValue(1).ToString();
}
}
}
cboxDB。根据屏幕截图中显示的错误,SelectedValue是Apple。你的SQL语句用简单的英语说:
选择标题(列)等于Apple(列)的TongHopDB(表)中的Title(列)和Post(列)
Apple
不是一个有效的列!
虽然可以简单地在cboxDB的值周围添加单引号,但您应该使用参数而不是连接字符串。http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/