1

我正在尝试根据 datagridview 中组合框的值从 SQL DB 的列中检索数据,我的代码是:

 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

有什么帮助吗??

4

1 回答 1

2

如果列的数据类型Name是 VARCHAR,则需要将值用单引号引起来,因为它是字符串文字。

string _val = dataGridView1.CurrentRow.Cells[0].Value.ToString();
string priceselected = ("SELECT price FROM Table_1 WHERE name='" + _val + "'");

但查询很容易受到SQL Injection. 请参数化查询,例如。

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();
于 2013-03-21T08:57:39.770 回答