|
p; sb.Append(@"Data Source=C:\Databases\orders.mdb;");
sb.Append("Provider=Microsoft.Jet.OLEDB.4.0;");
sb.Append("User ID=" + UID + ";Password=" + pwd);
string connString = sb.ToString();
conn.ConnectionString = connString;
conn.Open();
// Create the commands.
string cmdString = "Insert into Orders"
+ " (OrderID, OrderDate, CustomerID)"
+ " values(''''ABC60'''', #4/14/04#, 456)";
OleDbCommand cmdInsertOrder = new OleDbCommand(cmdString,conn);
//No need to insert OrderLineID, as that is an AutoNumber field.
cmdString = "Insert into OrderLines (OrderID, PartID, Quantity)"
+ " values(''''ABC60'''', 25, 10)";
OleDbCommand cmdInsertOrderLine =
new OleDbCommand(cmdString,conn);
cmdString = "Insert into PickList (OrderID, PartID, Quantity)"
+ " values(''''ABC60'''', 25, 10)";
OleDbCommand cmdCreatePickList =
new OleDbCommand(cmdString,conn);
// Begin the outer transaction and
// enlist the order-related commands.
OleDbTransaction tran = conn.BeginTransaction();
cmdInsertOrder.Transaction = tran;
cmdInsertOrderLine.Transaction = tran;
try
{
// Execute the commands
// to create the order and order
// line items.
cmdInsertOrder.ExecuteNonQuery();
cmdInsertOrderLine.ExecuteNonQuery();
// Create a nested transaction
// that allows the pick list
// creation to succeed or fail
// separately if necessary.
OleDbTransaction nestedTran = tran.Begin();
// Enlist the pick list command.
cmdCreatePickList.Transaction = nestedTran;
try
{
// Execute the pick list command.
cmdCreatePickList.ExecuteNonQuery();
// Commit the nested transaction.
nestedTran.Commit();
}
catch(OleDbException ex)
{
//Roll back the transaction.
nestedTran.Rollback();
// Add code to notify user or otherwise handle
// the fact that the procedure was only
// partially successful.
}
// Commit the outer transaction.
tran.Commit();
}
catch(OleDbException ex)
{
//Roll back the transaction.
tran.Rollback();
//Additional error handling if needed.
}
finally
{
// Close the connection.
conn.Close();
}
}
注: 引擎提供者为Microsoft OLE DB,其支持内嵌事务.
总结
事务是一个强有力的方式,用来保证数据修改任务得到合适的处理,同时ado.net让我们处理数据存取的能力更容易.当你构建你的数据读取和使用方案的时候考虑到这些情况,你将会保证你数据的完整性.
上一页 [1] [2] [C语言系列]NET 中C#的switch语句的语法 [系统软件]托拽Explore中的文件到VB.net的窗口 [系统软件]Boost库在XP+Visual C++.net中的安装 [常用软件]新配色面板:Paint.Net3.0RC1官方下载 [常用软件]用内建的“Net Meeting”聊天 [VB.NET程序]Henry的VB.NET之旅(三)—共享成员 [VB.NET程序]Henry的VB.NET之旅(二)—构造与析构 [VB.NET程序]Henry的VB.NET之旅(一)—失踪的窗体 [VB.NET程序]在托盘上显示Balloon Tooltip(VB.NET) [VB.NET程序]Henry手记-VB.NET中动态加载Treeview节点(二)
|