C# 根据c中datagridview中组合框的值从SQL server检索数据#
我试图根据datagridview中combo box的值从SQL DB中的列检索数据。我的代码是:C# 根据c中datagridview中组合框的值从SQL server检索数据#,c#,sql-server,C#,Sql Server,我试图根据datagridview中combo box的值从SQL DB中的列检索数据。我的代码是: private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs { using (SqlConnection conn = new SqlConnection("Data Source=POSSERVER\\SQLEXPRESS;Initial Catalog=ms;Integr
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs
{
using (SqlConnection conn = new SqlConnection("Data Source=POSSERVER\\SQLEXPRESS;Initial Catalog=ms;Integrated Security=True"))
{
string priceselected = ("SELECT price FROM Table_1 WHERE name=" + dataGridView1.CurrentRow.Cells[0].Value.ToString());
SqlCommand cmd = new SqlCommand(priceselected, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
我想把价格放在dataGridView1.CurrentRow.Cells[2]
但每次从组合框中选择项时,我都会得到一个sqlexception
有什么帮助吗 如果列
Name
的数据类型是VARCHAR,则需要使用单引号将值括起来,因为它是字符串文本
string _val = dataGridView1.CurrentRow.Cells[0].Value.ToString();
string priceselected = ("SELECT price FROM Table_1 WHERE name='" + _val + "'");
但是使用SQL注入
时,查询易受攻击。请执行参数化查询,例如
string _val = dataGridView1.CurrentRow.Cells[0].Value.ToString();
string priceselected = ("SELECT price FROM Table_1 WHERE name=@val");
SqlCommand cmd = new SqlCommand(priceselected, conn);
cmd.Parameters.AddWithValue("@val", _val);
conn.Open();
cmd.ExecuteNonQuery();
请详细分享您的异常您得到的异常或错误是什么?组合框中的值是什么?以下是一些未来的提示:调试代码;手动运行sql命令;了解如何避免sql注入。=)非常感谢它的工作,但现在我想在dataGridView1.CurrentRow.Cells[2]上显示该值