gpt4 book ai didi

c# - 使用 C# 在 SQL Server 上执行 sql 文件

转载 作者:行者123 更新时间:2023-11-30 13:52:43 24 4
gpt4 key购买 nike

我正在尝试创建一种在 SQL Server 数据库上运行 .sql 文件的方法。

我的代码是:

SqlConnection dbCon = new SqlConnection(connstr);
FileInfo file = new FileInfo(Server.MapPath("~/Installer/JobTraksDB.sql"));
StreamReader fileRead = file.OpenText();
string script = fileRead.ReadToEnd();
fileRead.Close();

SqlCommand command = new SqlCommand(script, dbCon);
try
{
dbCon.Open();
command.ExecuteNonQuery();
dbCon.Close();
}
catch (Exception ex)
{
throw new Exception("Failed to Update the Database, check your Permissions.");
}

但我不断收到有关“关键字‘GO’附近语法不正确”的错误消息我的 SQL 文件是这样开始的:(从 SQL Management Studio 生成)

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Job_Types](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
CONSTRAINT [PK_JobTypes] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

我应该如何执行这个脚本?

最佳答案

我们是这样做的:

    protected virtual void ExecuteScript(SqlConnection connection, string script)
{
string[] commandTextArray = System.Text.RegularExpressions.Regex.Split(script, "\r\n[\t ]*GO");

SqlCommand _cmd = new SqlCommand(String.Empty, connection);

foreach (string commandText in commandTextArray)
{
if (commandText.Trim() == string.Empty) continue;
if ((commandText.Length >= 3) && (commandText.Substring(0, 3).ToUpper() == "USE"))
{
throw new Exception("Create-script contains USE-statement. Please provide non-database specific create-scripts!");
}

_cmd.CommandText = commandText;
_cmd.ExecuteNonQuery();
}

}

使用一些文件读取功能加载脚本的内容。

关于c# - 使用 C# 在 SQL Server 上执行 sql 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1565674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com