[2
使用smo 执行SQL脚本文件
使用系统; 使用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:
此方法提供了一种干净有效的方法来处理C#应用程序中的复杂SQL脚本。 使用语句通过自动关闭数据库连接来确保正确的资源管理。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3