我试图在同一个方法中执行两个查询,但它给了我这个例外。我可以通过声明新命令来获得此异常的红色但是有没有办法使用相同的命令?
string id="hi";
connection.Open();
OleDbCommand command1 = new OleDbCommand();
command1.Connection = connection;
string query1 = "select * from products where category='" + comboBox1.Text + "' and subcategory = '" + comboBox2.Text + "' and sizes='" + comboBox3.Text + "'";
command1.CommandText = query1;
OleDbDataReader reader = command1.ExecuteReader();
while (reader.Read())
{
id = reader[0].ToString();
}
textBox1.Text = id;
string query = "insert into category_in (category_id,amount,amount_in) values ('"+ id+"' ,500,300)";
command1.CommandText = query;
command1.ExecuteNonQuery();
MessageBox.Show("saved");
connection.Close();
答案 0 :(得分:0)
完成后,您需要关闭OleDbDataReader
对象:
// previous code omitted for brevity
//
while (reader.Read())
{
id = reader[0].ToString();
}
// need to close reader
//
reader.Close();
// run your other query (omitted for brevity)
正如您对问题的评论所述,构建查询的方式极易受到SQL注入攻击。 Parameterize your query正确的方式。
根据德米特里的评论,我完全同意。在OleDbDataReader
块中包裹您的using
对象,以便在完成阻止后致电OleDbDataReader.Dispose()
:
using (OleDbDataReader reader = command1.ExecuteReader())
{
// ...
}
答案 1 :(得分:0)
首次执行后需要关闭阅读器,因此代码就像这样
string id="hi";
connection.Open();
OleDbCommand command1 = new OleDbCommand();
command1.Connection = connection;
string query1 = "select * from products where category='" + comboBox1.Text + "' and subcategory = '" + comboBox2.Text + "' and sizes='" + comboBox3.Text + "'";
command1.CommandText = query1;
OleDbDataReader reader = command1.ExecuteReader();
while (reader.Read())
{
id = reader[0].ToString();
}
textBox1.Text = id;
////////code for closing the reader/////////////
reader.Close();
///////////////
string query = "insert into category_in (category_id,amount,amount_in) values ('"+ id+"' ,500,300)";
command1.CommandText = query;
command1.ExecuteNonQuery();
MessageBox.Show("saved");
connection.Close();