using System;
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
namespace ScriptRunner
{
class Program
{
static void Main(string[] args)
{
var script = File.ReadAllText("Test.sql");
const string sqlConnectionString = @"Data Source=my\ds;
Initial Catalog=myic;
Connection Timeout=0;
Integrated Security=true";
SqlConnection connection = null;
Server server = null;
try
{
connection = new SqlConnection(sqlConnectionString);
server = new Server(new ServerConnection(connection));
connection.Open();
server.ConnectionContext.BeginTransaction();
server.ConnectionContext.ExecuteNonQuery(script);
server.ConnectionContext.CommitTransaction();
}
catch { server.ConnectionContext.RollBackTransaction(); }
finally { connection?.Dispose(); }
}
}
}
除交易外,一切正常。该命令刚刚运行,如果有错误,之前的所有内容都已经在数据库中。如何使交易在这里工作?
[编辑] 当我更改代码以在SqlConnection级别打开事务时(here建议它,应该没有区别):
SqlTransaction transaction = null;
try
{
connection = new SqlConnection(sqlConnectionString);
server = new Server(new ServerConnection(connection));
connection.Open();
transaction = connection.BeginTransaction();
server.ConnectionContext.ExecuteNonQuery(script);
transaction.Commit();
}
抛出InvalidOPexception:“当分配给命令的连接处于挂起的本地事务中时,ExecuteNonQuery要求命令具有事务。该命令的Transaction属性尚未初始化。” < / p>
但我没有看到可以访问命令对象的地方。
答案 0 :(得分:1)
我遇到了同样的问题“ExecuteNonQuery需要命令进行交易......” 似乎如果为ServerConnection执行begin / commit事务,而不是为SqlConnection执行,那么一切正常。
...
SqlConnection connection = new SqlConnection(sqlConnectionString);
ServerConnection srvCon = new ServerConnection(connection);
try
{
server = new Server(srvCon);
srvCon.BeginTransaction();
server.ConnectionContext.ExecuteNonQuery(script);
srvCon.CommitTransaction();
}
catch
{
srvCon.RollBackTransaction();
}
...