”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 在C#中如何执行包含多条语句的SQL脚本文件?

在C#中如何执行包含多条语句的SQL脚本文件?

发布于2025-04-16
浏览:904

[2

使用smo How Can I Execute an SQL Script File Containing Multiple Statements in C#?
执行SQL脚本文件

本指南演示了如何在C#应用程序中执行包含多个语句(可能跨越几行)的SQL脚本文件。 我们将在此任务中利用Microsoft SQL Server Management对象(SMO)。

这是一个C#代码示例:

使用系统; 使用Microsoft.sqlserver.management.smo; 使用microsoft.sqlserver.management.common; 使用System.io; 公共类SQLSCriptrunner { public void runscript(字符串脚本路径,字符串ConnectionsTring) { //从文件中读取整个SQL脚本。 字符串sqlscript = file.readallText(ScriptPath); //建立数据库连接。 使用(SQLConnection Connection = new SQLConnection(ConnectionsTring)) { //使用连接创建服务器对象。 Server Server = new Server(new ServerConnection(Connection)); //使用SMO的executenonquery执行脚本。 server.connectioncontext.executenonquery(sqlscript); } } }

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

public class SqlScriptRunner
{
    public void RunScript(string scriptPath, string connectionString)
    {
        // Read the entire SQL script from the file.
        string sqlScript = File.ReadAllText(scriptPath);

        // Establish a database connection.
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            // Create a Server object using the connection.
            Server server = new Server(new ServerConnection(connection));

            // Execute the script using SMO's ExecuteNonQuery.
            server.ConnectionContext.ExecuteNonQuery(sqlScript);
        }
    }
}

实例化和execute:
    创建一个
  1. sqlscriptrunner 的实例,并调用方法,为您的SQL Script File和一个有效的数据库连接String。 此方法提供了一种干净有效的方法来处理C#应用程序中的复杂SQL脚本。 使用语句通过自动关闭数据库连接来确保正确的资源管理。
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3