0

Actually I want to make the button click and execute those 2 queries in one-time manner.

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();

How do I execute multiple with this code? I try to add some data to the existing table which is already inserted. I am newbie in C# and start to understand some of the code.

Jawad
  • 11,028
  • 3
  • 24
  • 37
Amirul Asyraf
  • 91
  • 5
  • 14
  • 5
    Before you do that, try one sql command without a glaring *sql injection* attack vector by using parameterized query – TheGeneral Feb 12 '20 at 03:31

1 Answers1

1

You cannot reuse the same connection with multiple MySqlDataReader objects simultaneously: https://mysqlconnector.net/troubleshooting/connection-reuse/

Since your code doesn't actually need the MySqlDataReader, a simple fix is to use ExecuteNonQuery to execute your UPDATE statements.

You should also use parameterised queries to avoid SQL injection and using statements to close the connection automatically

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");
}
Bradley Grainger
  • 27,458
  • 4
  • 91
  • 108