如何在单个 SQL 连接中运行多个 SQL 命令?

编程入门 行业动态 更新时间:2024-10-27 14:30:25
本文介绍了如何在单个 SQL 连接中运行多个 SQL 命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在创建一个项目,我需要在单个 SQL 连接中运行 2-3 个 SQL 命令.这是我写的代码:

I am creating a project in which I need to run 2-3 SQL commands in a single SQL connection. Here is the code I have 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','" + 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(); }

我已尝试消除错误,但我发现连接不会进入其他状态.请检查代码并建议是否有任何错误或任何其他解决方案.

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

更多推荐

如何在单个 SQL 连接中运行多个 SQL 命令?

本文发布于:2023-11-06 17:49:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564379.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   命令   如何在   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!