如何从ASP.NET C#一次执行多个SQL命令 [英] How to execute multiple SQL commands at a time from ASP.NET C#

查看:67
本文介绍了如何从ASP.NET C#一次执行多个SQL命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

When i execute the code its giving runtime error.

But when i execute same commands which i took commands from debugging mode and paste in SQL server. It is executing fine without errors.

Please give me the solution.




string s = "create database dbTest  \r\n GO \r\n Use dbTest \r\n GO";
        SqlCommand cmd = new SqlCommand(s, con);
        cmd.CommandType = CommandType.Text;
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();`





我尝试过:



string s =创建数据库dbTest \\\ GO \\\\ n使用dbTest \\\ GO;

SqlCommand cmd = new SqlCommand(s,con);

cmd.CommandType = CommandType.Text;

con.Open();

cmd.ExecuteNonQuery();

con.Close();`



What I have tried:

string s = "create database dbTest \r\n GO \r\n Use dbTest \r\n GO";
SqlCommand cmd = new SqlCommand(s, con);
cmd.CommandType = CommandType.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();`

推荐答案

GO是一个SQL-Server-Management-Studio特定命令,而不是T-SQL的一部分。



如果你想使用带有GO命令的SQL脚本,请参考:

c# - 执行一个大型SQL脚本(使用GO命令) - Stack Overflow [ ^ ]



否则你必须单独执行这些语句(我建议使用使用 -statements for Sql *** * -objects):



"GO" is a SQL-Server-Management-Studio specific command and not part of T-SQL.

If you would want to use SQL-scripts with "GO"-commands please refer to this:
c# - Execute a large SQL script (with GO commands) - Stack Overflow[^]

Otherwise you would have to execute these statements separately (and I suggest using using-statements for Sql****-objects):

using (var connection = new SqlConnection("your connection string here"))
{
    connection.Open();

    using (var command = connection.CreateCommand())
    {
        command.CommandText = "CREATE DATABASE dbTest;";
        command.ExecuteNonQuery();

        command.CommandText = "USE dbTest;";
        command.ExecuteNonQuery();
    }
}



连接字符串最好不要在指定位置硬编码,而应从配置文件中读取。



请注意,USE命令只会影响同一连接上的以下命令,所以在这个例子中它很没用。


The connection string should best not be hardcoded at the indicated position but be read from a configuration file.

Note that the "USE"-command will affect only the following commands on the same connection, so in this example it's pretty useless.


这篇关于如何从ASP.NET C#一次执行多个SQL命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆