我希望在 PowerShell 中将一些 SQL 查询作为事务执行。但是,我遇到错误并且找不到合适的答案。除了错误之外,BeginTransaction() 和 CommitTransaction() 是在 Powershell 中执行事务的方法吗?Intellisense 似乎没有显示 CommitTransaction() 方法。
错误:
Exception calling "ExecuteNonQuery" with "0" argument(s): "ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been
initialized
Run Code Online (Sandbox Code Playgroud)
代码:
try {
#SQL Connection
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "Server=$server,1433;Initial Catalog=$Database;Persist Security Info=False;User ID=$UserID;Password=$Password;MultipleActiveResultSets=true;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
#Begin Transaction
$Connection.BeginTransaction()
#INSERT into PROJECT table
$input_2 = $projectName
$input_3 = $blobUri + $configFileName
$input_4 = $key
$input_5 = $projectType
$input_6 = $projectIsActive
$sql =
"
begin
INSERT INTO PROJECT
([PROJECT_NAME],[CONFIGURATION_LOCATION],[ENCRYPTION_KEY],[PROJECT_TYPE],[IS_ACTIVE],[CREATED_DATETIME])
select '$input_2', '$input_3', '$input_4', '$input_5', '$input_6', cast(CONVERT(datetimeoffset,GETDATE()) AT TIME ZONE 'AUS Eastern Standard Time' as datetime)
end
"
$Command.CommandText = $sql
$Command.ExecuteNonQuery()
#Get Project ID from PROJECT table
$sql =
"
begin
SELECT TOP 1 PROJECT_ID FROM PROJECT WHERE PROJECT_NAME='$projectName'
end
"
$Command.CommandText = $sql
$projectID = $Command.ExecuteScalar()
#Commit Transaction
$Connection.CommitTrasaction()
#Close Connection
$Connection.Close()
}
Catch {
throw
}
Run Code Online (Sandbox Code Playgroud)
您必须将Transaction的 属性设置SqlCommand为 所返回的事务对象BeginTransaction:
$command.Transaction = $connection.BeginTransaction()
try {
$command.ExecuteNonQuery()
$command.Transaction.Commit()
}
catch {
try {
$command.Transaction.Rollback()
}
catch {
# Microsoft recommends to catch and log and/or ignore rollback exceptions
}
throw
}
Run Code Online (Sandbox Code Playgroud)
注意:回滚本身也可能会抛出异常。您可能想在它周围放置另一个 try-catch。回滚错误通常可以安全地忽略(或只是记录),事务可能已经被回滚。
| 归档时间: |
|
| 查看次数: |
4719 次 |
| 最近记录: |