实际上,我想单击按钮并以一次性方式执行这两个查询。
string Query = "UPDATE harga_semasa SET we_buy='" + this.textBox1.Text + "',we_sell='" + this.textBox2.Text + "', idharga_semasa='" + this.label5.Text + "' WHERE type='" + this.label1.Text + "';";
string Query2 = "UPDATE harga_semasa SET we_buy='" + this.textBox3.Text + "',we_sell='" + this.textBox4.Text + "', idharga_semasa='" + this.label10.Text + "' WHERE type='" + this.label4.Text + "';";
MySqlConnection MyConn2 = new MySqlConnection(ConString);
MySqlCommand MyCommand2 = new MySqlCommand(Query2, MyConn2);
MySqlCommand MyCommand1 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
MyReader2 = MyCommand1.ExecuteReader();
MessageBox.Show("Data Updated");
while (MyReader2.Read())
{
}
MyConn2.Close();
如何使用此代码执行多个?我尝试将一些数据添加到已插入的现有表中。我是C#的新手,开始了解一些代码。
答案 0 :(得分:1)
您不能同时对多个MySqlDataReader
对象重新使用同一连接:https://mysqlconnector.net/troubleshooting/connection-reuse/
由于您的代码实际上不需要MySqlDataReader
,因此一个简单的解决方法是使用ExecuteNonQuery
执行您的UPDATE
语句。
您还应该使用参数化查询来避免SQL注入和using
语句自动关闭连接
using (var connection = new MySqlConnection(ConString))
{
connection.Open();
using (var command = new MySqlCommand(@"UPDATE harga_semasa SET we_buy=@we_buy, we_sell=@we_sell, idharga_semasa=@idharga_semasa WHERE type=@type;", connection)
{
command.Parameters.AddWithValue("@we_buy", this.textBox1.Text);
command.Parameters.AddWithValue("@we_sell", this.textBox2.Text);
command.Parameters.AddWithValue("@idharga_semasa ", this.label5.Text);
command.Parameters.AddWithValue("@type", this.label1.Text);
// use this to run the query (without MySqlDataReader)
command.ExecuteNonQuery();
}
// execute your second query the same way here
MessageBox.Show("Data Updated");
}