如何运行在单个SQL连接多个SQL命令?
问题描述:
我创造的一个项目中,我需要在一个SQL连接朗姆酒2-3 SQL命令。 这里是code我写的:
I am creating a project in which I need to rum 2-3 sql command in single sql connection. Here is the code I had written :
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\project.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from " + mytags.Text + " ", con);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.Read())
{
con.Close();
con.Open();
SqlCommand cmd1 = new SqlCommand("insert into " + mytags.Text + " values ('fname.lname@gmail.com','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','"+mytags.Text+"')", con);
cmd1.ExecuteNonQuery();
label.Visible = true;
label.Text = "Date read and inserted";
}
else
{
con.Close();
con.Open();
SqlCommand cmd2 = new SqlCommand("create table " + mytags.Text + " ( session VARCHAR(MAX) , Price int , Description VARCHAR(MAX), Date VARCHAR(20),tag VARCHAR(10))", con);
cmd2.ExecuteNonQuery();
con.Close();
con.Open();
SqlCommand cmd3 = new SqlCommand("insert into " + mytags.Text + " values ('" + Session + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + mytags.Text + "')", con);
cmd3.ExecuteNonQuery();
label.Visible = true;
label.Text = "tabel created";
con.Close();
}
我试图删除错误,我该连接不会到别的condition.Please审查code和建议如果有任何错误或任何其他解决方案这一点。
I have tried to remove the error and I got that the connection is not going to else condition.Please review the code and suggest if there is any mistake or any other solution for this.
答
只要改变 SqlCommand.CommandText
,而不是创建一个新的的SqlCommand
每次。没有必要以关闭和重新打开连接
Just change the SqlCommand.CommandText
instead of creating a new SqlCommand
every time. There is no need to close and reopen the connection.
// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();
// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();