//初始化
SqlConnection sqlConnection = new SqlConnection();
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
//建立并开启事务
sqlConnection.Open();
SqlTransaction sqlTransaction = sqlConnection.BeginTransaction();
sqlCommand.Transaction = sqlTransaction;
try
{
//利用sqlcommand进行数据操作
...
//提交事务
sqlTransaction.Commit();
}
catch(Exception ex)
{
//出错后回滚事务
sqlTransaction.Rollback();
}
sqlConnection.Close();