gpt4 book ai didi

c# - 如何从 C# 执行 .sql?

转载 作者:可可西里 更新时间:2023-11-01 03:13:09 26 4
gpt4 key购买 nike

对于某些集成测试,我想连接到数据库并运行一个 .sql 文件,该文件具有实际运行测试所需的架构,包括 GO 语句。如何执行 .sql 文件? (或者这是完全错误的方法吗?)

我找到了 a post in the MSDN forum显示此代码:

using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True";
FileInfo file = new FileInfo("C:\\myscript.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
}
}
}

但是在最后一行我得到了这个错误:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeInitializationException: The type initializer for '' threw an exception. ---> .ModuleLoadException: The C++ module failed to load during appdomain initialization. ---> System.DllNotFoundException: Unable to load DLL 'MSVCR80.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E).

我被告知去从某个地方下载那个 DLL,但这听起来很老套。有没有更清洁的方法?还有另一种方法吗?我做错了什么?

我正在使用 Visual Studio 2008、SQL Server 2008、.Net 3.5SP1 和 C# 3.0 执行此操作。

最佳答案

using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

您不应该需要 SMO 来执行查询。请尝试改用 SqlCommand 对象。删除这些 using 语句。使用此代码执行查询:

 SqlConnection conn = new SqlConnection(sqlConnectionString);
SqlCommand cmd = new SqlCommand(script, conn);
cmd.ExecuteNonQuery();

此外,删除对 SMO 的项目引用。注意:您需要正确清理资源。

更新:

ADO.NET 库 do not support the 'GO' keyword .看起来您的选择是:

  1. 解析脚本。删除“GO”关键字并将脚本拆分为单独的批处理。将每个批处理作为其自己的 SqlCommand 执行。
  2. 将脚本发送到 shell 中的 SQLCMD(David Andres 的回答)。
  3. 像博文中的代码一样使用 SMO。

实际上,在这种情况下,我认为 SMO 可能是最佳选择,但您需要找出找不到 dll 的原因。

关于c# - 如何从 C# 执行 .sql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1449646/

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