数据库事务(Database Transaction)的ADO.NET(C#/VB)实现
数据库事务(Database Transaction),是指作为单个逻辑工作单元执行的一系列操作,要么完全地执行,要么完全地不执行。
那么,数据库事务在什么场景使用呢?
举个栗子
设想网上购物的一次交易,其付款过程至少包含以下几个步骤:
1.更新客户所购商品的库存信息。
2.保存客户付款信息-可能包括与付款系统(银行、支付宝或微信等)的交互。
3.生成订单并保存到数据库中。
4.更新用户相关信息,例如购物数量等。
正常情况下,这4个步骤都能有序执行,但是,如果在这一系列过程中任何一个环节出错,就可能出现库存扣除了,但是交易失败的问题。而数据库事务正是用来保证这种情况下交易的平稳性和可预测性的技术。
言归正传,现在讲重点,ADO.NET的库存事务实现,ADO.NET在库存事务操作时使用SqlTransaction 类。更多信息请查看visual studio帮助
SqlTransaction 类:表示要在 SQL Server 数据库中处理的 Transact-SQL 事务。无法继承此类。
语法
C#:public sealed class SqlTransaction : DbTransaction
VB:Public NotInheritable Class SqlTransaction Inherits DbTransaction
备注
应用程序通过在 SqlConnection 对象上调用 BeginTransaction 来创建 SqlTransaction 对象。 对 SqlTransaction 对象执行与该事务关联的所有后续操作(例如提交或中止该事务)。
说明
在提交或回滚 SqlTransaction 时,应始终使用 Try/ Catch 进行异常处理。 如果连接终止或事务已在服务器上回滚,则 Commit 和 Rollback 都会生成 InvalidOperationException。
C#示例:
private static void ExecuteSqlTransaction(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
// Start a local transaction.
transaction = connection.BeginTransaction("SampleTransaction");
// Must assign both transaction object and connection
// to Command object for a pending local transaction
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
command.ExecuteNonQuery();
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
command.ExecuteNonQuery();
// Attempt to commit the transaction.
transaction.Commit();
Console.WriteLine("Both records are written to database.");
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
}
}
VB示例:
Private Sub ExecuteSqlTransaction(ByVal connectionString As String)
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim command As SqlCommand = connection.CreateCommand()
Dim transaction As SqlTransaction
' Start a local transaction
transaction = connection.BeginTransaction("SampleTransaction")
' Must assign both transaction object and connection
' to Command object for a pending local transaction.
command.Connection = connection
command.Transaction = transaction
Try
command.CommandText = _
"Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
command.ExecuteNonQuery()
command.CommandText = _
"Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"
command.ExecuteNonQuery()
' Attempt to commit the transaction.
transaction.Commit()
Console.WriteLine("Both records are written to database.")
Catch ex As Exception
Console.WriteLine("Commit Exception Type: {0}", ex.GetType())
Console.WriteLine(" Message: {0}", ex.Message)
' Attempt to roll back the transaction.
Try
transaction.Rollback()
Catch ex2 As Exception
' This catch block will handle any errors that may have occurred
' on the server that would cause the rollback to fail, such as
' a closed connection.
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType())
Console.WriteLine(" Message: {0}", ex2.Message)
End Try
End Try
End Using
End Sub
如果大家觉得这些示例还是麻烦的话,可以花9.9去购买一个pgzzCnn.dll,该库使用炒鸡简单,包含了几乎所有的数据库操作,支持SqlClient、OleDb和Odbc方式,支持连接SQLSERVER、ACCESS、Oracle以及MYSQL,支持SELECT、UPDATE、INSERT操作,特别是支持批量写入(datatable到数据库)和数据库事务处理。
使用示例:
公共模块声明:
Private strConn As String = "Data Source=服务器实例;Initial Catalog=数据库;User ID=sa;Password=密码"
Public Csql As pgzz.sqlserver ’ 不同数据源可声明为对应的方式oledb/odbc
获取表:
Dim strSQL As String = "select * from 表1 where 查询条件"
Dim tt As DataTable = Csql.GetTable(strSQL)
更新或插入:
Dim strSQL As String = "update 表 set 字段=’值’ where 条件"
Dim exCount As integer = Csql. DoSql (strSQL) ‘dosql返回受影响的行数
批量插入(sqlserver支持,其它不支持):
dim sw as long = Csql. DoSql(newTable,tableName) ‘这里返回的是执行的时间(ms),如返回0则代表出错了。
数据库事务:
Dim strSQL As String
Dim strL As New List(Of String)
strSQL = " insert into 表1(字段1,字段2……) values(值1,……)"
strL.Add(strSQL)
strSQL = " update表2 set 字段1=值 where 条件"
strL.Add(strSQL)
If Csql.DoSql(strL) Then
‘执行成功!
Else
‘执行失败!
End If
是不是炒鸡简单呢?
9块9,买不了吃亏,买不了上当,pgzzCnn,你值得拥有(需要源码可以跟店主私聊)。
闲鱼链接:
https://market.m.taobao.com/app/idleFish-F2e/widle-taobao-rax/page-detail?wh_weex=true&wx_navbar_transparent=true&id=586152596728&ut_sk=1.WfFNPGwSx70DACo2hZcTFezZ_21407387_1548072402925.Copy.detail.586152596728.320966645&forceFlush=1
或在闲鱼搜索
“数据库使用程序集”