这是我的代码,在Combobox
中选择一个连接字符串时效果很好如何在多个连接中执行相同的SQL查询,只需一个按钮点击一个按钮?
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();
}
}
答案 0 :(得分:4)
您的代码存在问题,例如Sql Injection,您可以使用参数化查询进行修复。
您没有使用Text
的{{1}}属性。修复您的命名并且不要将textbox1用于控件名称。命名很重要,所以其他程序员可以理解。对于您的数据库表也是如此,textbox1
不是合适的名称。
当您处于Table1
阻止时,您不需要Close()
该连接。使用自动执行此操作。此外,当您创建using
对象时,您可以打开连接,如果对其进行检查则无需进行。
SqlConnection