aarriiaann aarriiaann - 1 month ago 9
C# Question

Execute SQL in multiple connections c#

This is the Code i have and it works well when choose one connection string in Combobox

How can i execute same SQL query in multiple connections with one button click not one by one??

public string connstring = "";
private void cmbSrv_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbSrv.SelectedIndex == 0)
{
connstring = @"Data Source=tcp:10.1.0.100;Initial Catalog=Database1;User ID=user;Password=pass;MultipleActiveResultSets=true;";
}
else if (cmbSrv.SelectedIndex == 1)
{
connstring = @"Data Source=tcp:10.0.0.100;Initial Catalog=Database2 ;User ID=user;Password=pass;MultipleActiveResultSets=true;";

}
}
private void btnKonfirm_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(connstring))

{
SqlCommand cmd1 = new SqlCommand();

if (connection.State == ConnectionState.Closed)
{
connection.Open();
}

SqlCommand command1 =
new SqlCommand("DELETE FROM TABLE1 WHERE ID="+textbox1+"", connection);



command1.ExecuteNonQuery();


connection.Close();
}
}

Answer

You have some problems with your code like Sql Injection, you can fixed with parameterized queries.

You are not taking the Text property of your textbox1. Fix your naming and don't use textbox1 for control names. Naming is important, so you can be understand by other programmers. Same is true for your database table, Table1 is not appropriate name.

You don't need to Close() the connection when you are in using block. Using do this automatically. Also when you create an SqlConnection object you can open a connection, there is no need to make if checks about it.

public void ConfirmBtn_Click(object sender, EventArgs e)
{
     string connString1 = "FirstConnectionSTring";
     string connString2 = "SecondConnectionSTring";

     ExecuteNonQuery(connString1);
     ExecuteNonQuery(connString2);
}

public void ExecuteNonQuery(string connString)
{
    using (SqlConnection connection = new SqlConnection(connString))
    {

         connection.Open();
         SqlCommand cmd =
                    new SqlCommand("DELETE FROM TABLE1 WHERE ID=@ID", connection);

         cmd.Parameters.AddWithValue("@ID", textbox1.Text);         

         cmd.ExecuteNonQuery();

    }
}