SqlConnection myConnection = new SqlConnection(@"server=服务器;uid=用户名;pwd=密码;database=数据库;");
myConnection.Open();
SqlTransaction myTrans = myConnection.BeginTransaction();
// 为事务创建一个命令
SqlCommand myCommand = new SqlCommand();
myCommand.Connection=myConnection;
myCommand.Transaction = myTrans;
//执行数据库操作部分
myTrans.Commit();
Console.WriteLine("Both records are written to database.");
}
catch(Exception e)
{
myTrans.Rollback();
Console.WriteLine(e.ToString());
Console.WriteLine("Neither record was written to database.");
}
finally
{
myConnection.Close();
}