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

标签 c# sql sql-server sql-server-2008

对于某些集成测试,我想连接到数据库并运行一个 .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/

相关文章:

c# - 通用 LINQ 查询谓词?

c# - 隐式强制转换对委托(delegate)类型推断的意外影响

php - 当Select列多于Insert列时如何处理查询?

sql - 在 SQL Server 中查找重复行

c# - Entity Framework Core 6.0.13 - 为连接实体插入负外键值

c# - Selenium c# : Wait Until Element is Present Without Waiting the Time Given, 否则超时

c# - 从异步方法立即抛出

mysql - 只允许一个唯一的外键作为主键

java - 插入查询中的数组列表

sql - 使用 select 将行添加到查询结果