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.

1
  • 5
    Before you do that, try one sql command without a glaring sql injection attack vector by using parameterized query Commented Feb 12, 2020 at 3:31

1 Answer 1

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");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.