asp.net – 如何通过ADO.NET运行我的.sql脚本文件?

我想通过ADO.NET使用我的ASP.NET网站运行我的.sql脚本文件.它怎么可能不起作用?

当我尝试

'dbScript is a string and contains contents of the .sql file'
Dim cmd As New sqlCommand(dbScript,con)
Try
    con.open()
    cmd.ExecuteNonQuery()
Catch ex As Exception
Finally
    con.Close()
    cmd.dispose()
End Try

GO语句在脚本中执行时会出现异常.我该如何解决这个问题?

解决方法

请参阅我关于 Handling GO Separators in SQL – The Easy Way的博文.诀窍是使用 SMO’s ExecuteNonQuery()方法.例如,这里有一些代码将运行目录中的所有脚本,而不管GO分隔符:
using System;
    using System.IO;
    using System.Data.sqlClient;
    using System.Collections.Generic;

    //Microsoft.sqlServer.Smo.dll
    using Microsoft.sqlServer.Management.Smo;
    //Microsoft.sqlServer.ConnectionInfo.dll
    using Microsoft.sqlServer.Management.Common;

    public class RunAllsqlSriptsInDirectory
    {
        public static void Main()
        {
            string scriptDirectory = "c:\\temp\\sqltest\\";
            string sqlConnectionString = "Integrated Security=sspI;" + 
                "Persist Security Info=True;Initial Catalog=northwind;Data Source=(local)";
            DirectoryInfo di = new DirectoryInfo(scriptDirectory);
            FileInfo[] rgFiles = di.GetFiles("*.sql");
            foreach (FileInfo fi in rgFiles)
            {
                FileInfo fileInfo = new FileInfo(fi.FullName);
                string script = fileInfo.OpenText().ReadToEnd();
                sqlConnection connection = new sqlConnection(sqlConnectionString);
                Server server = new Server(new ServerConnection(connection));
                server.ConnectionContext.ExecuteNonQuery(script);
            }
        }
    }

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....