0
我试图做的是,当你删除一个记录在sql-server数据库时,它将首先检查数量是否大于零,如果是的话它不会删除记录。我认为它的工作,但我不断收到这个错误“DataReader必须先关闭”,无论我做什么。任何帮助,将不胜感激。如何解决这个错误? DataReader必须先关闭
private void btnDelete_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=DESKTOP-MQKIBSK\\SQLEXPRESS;Initial Catalog=inventory2;Integrated Security=True");
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT Quantity FROM Items WHERE (Barcode = '" + dataGridView1.CurrentRow.Cells[0].Value + "')", cn);
SqlDataReader quantityRdr = null;
quantityRdr = cmd.ExecuteReader();
while (quantityRdr.Read())
{
string squantity = quantityRdr["Quantity"].ToString();
int x = Int32.Parse(squantity);
if (x > 0)
{
MessageBox.Show("You can't delete this record");
}
else
{
DialogResult r = MessageBox.Show("Are you sure you want to delete this record?", "Delete", MessageBoxButtons.YesNo);
if (r == DialogResult.Yes)
{
SqlCommand cmd1 = new SqlCommand(@"DELETE FROM Items where (Barcode = '" + dataGridView1.CurrentRow.Cells[0].Value + "')", cn);
MessageBox.Show("Item deleted!");
cmd1.ExecuteNonQuery();
fill();
}
else
{
MessageBox.Show("invalid");
}
}
}
你在哪一行得到错误?另一方面,为什么不先关闭DataReader? –
在cmd1.executenonquery();线。但它现在好了,感谢下面的答案 – FutureDev
Sql Injection的精彩模式。我甚至不需要知道该列的名称。这足以输入_'OR 1 = 1'--_尽快搜索关于Sql注入 – Steve