如何使用事物(SqlTransaction)来处理下面的命令:SqlCommand sc = new SqlCommand("delete from t_user where userid=1",sqlConn);
存储过程
SqlCommand sc = new SqlCommand("exec sp_delete "+id,sqlConn);
SqlCommand sc = new SqlCommand("开始事务 delete from t_user where userid=1 提交事务",sqlConn);
帮顶。
有两种方法,
一:采用.NET的类库实现事务处理:
private static void ExecuteSqlTransaction(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
transaction = connection.BeginTransaction("SampleTransaction");
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText =
"Insert into Department (ID, Name) VALUES (1, '工程部')";
command.ExecuteNonQuery();
command.CommandText =
"Insert into Users(ID, Name,DepartmentID) VALUES (1, 'xyz',1)";
command.ExecuteNonQuery();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
}
}
}
二:写在SQL命令里, 用SQL实现
BEGIN TRANSACTION XXX
--sql Here
COMMIT TRANSACTION XXX
END
以上两位回答不错,帮顶。