Protecting Your Data Integrity with Transactions in ADO.NET

vxe-table一个基于 Vxe UI 的 PC 端表格组件 一个基于 Vxe UI 的 PC 端表格组件,支持增删改查的可编辑表格,支持 Excel 复制粘贴、数据透视表、虚拟列表高性能的企业级表格解决方案 设计理念 面向现代浏览器,不支持 IE 双向数据流的设计,在渲染器或自定义扩展中支持直接操作数据值,达到最高效的简洁 API 设计 按需加载、自定义主题样式 分支说明 v3 分支和 v4 分支功能与 API 保持同步更新 v3 分支对应 vue 2.6~2.7 版本,v3.9+ 为长期维护版本 v4 分支对应 vue 3.x 版本,v4.7+ 为长期维护版本 立即下载

 

 

 

Protecting Your Data Integrity with Transactions in ADO.NET

Christa Carpentiere

May 2004

Applies to:
Microsoft? ADO.NET
Microsoft? .NET Framework

Summary: Transactions are a key feature for maintaining data integrity when modifying data. Get an overview of transactions and their importance, then learn how to use them to protect data in your .NET applications. (19 printed pages)

Contents

Introduction
Anatomy of a Transaction
Transactions with ADO.NET
Implementing Transactions
Conclusion

Introduction

Transactions are a feature offered by most enterprise-class databases for making sure data integrity is maintained when data is modified. Maintaining data integrity protects the quality of the data that your organization relies upon; after all, when you generate a report or engage in some other data-driven procedure, you want to know that the information you are working with is correct.

A successful transaction must pass the "ACID" test, that is, it must be:

·                     Atomic – All statements in the transaction either completed successfully or they were all rolled back. The task that the set of operations represents is either accomplished or not, but in any case not left half-done, to the detriment of your data.

·                     Consistent – All data touched by the transaction is left in a logically consistent state. For example, if inventory numbers were decremented in one table, there has to be a related order that consumed that inventory. The inventory can't just disappear.

·                     Isolated – The transaction must affect data without interfering with other concurrent transactions, or being interfered with by them. This prevents transactions from making changes to data based on uncommitted information, for example changes to a record that are subsequently rolled back. Most databases use locking to maintain transaction isolation.

·                     Durable – The data changes enacted by the transaction are permanent, and will persist through a system failure.

The classic example is submitting an order to an order entry system—you have to check the customer's credit level, create an order record, create order line item records, decrement the order items from inventory, create a ship request, and more. If one or more of those steps fail but the rest succeed, you can end up with inconsistent data in the form of orphaned records, unreliable inventory numbers, and so forth. Using transactions appropriately prevents this kind of thing from happening. And that's good for your DBA, your company, and your job security.

That said, remember to only use transactions where necessary. Managing transactions will add some overhead to the system. Using transactions can also increase the number and extent of locks (or other isolation mechanism, depending on the database) used in the system, which can lead to concurrency issues. Consider such things as whether the work encapsulated in the transaction must be performed as an atomic unit, whether there are consequences to it being performed in stages, and what will happen if it only partially completes.

Transactions can be implemented on the server side, using whatever variant of SQL is native to the database, or they can be handled using ADO.NET in the calling application. This article will address implementing database transactions with the ADO.NET data providers. I'll start by taking a look at what transactions are and how they affect your interactions with the database. I'll then take a look at the classes that the .NET Framework provides to assist you in creating and managing transactions in your data access code, and some common scenarios for their use.

Anatomy of a Transaction

A transaction at its most basic level consists of two required steps—Begin, and then either Commit or Rollback. The Begin call defines the start of the transaction boundary, and the call to either Commit or Rollback defines the end of it. Within the transaction boundary, all of the statements executed are considered to be part of a unit for accomplishing the given task, and must succeed or fail as one. Commit (as the name suggests) commits the data modifications if everything was successful, and Rollback undoes the data modifications if an error occurs. All of the .NET data providers provide similar classes and methods to accomplish these operations.

Isolation Levels

Isolation levels are used by transactions to determine how restrictive the transaction is in regards to its isolation behavior. The more restrictive the isolation level, the more stringently the data affected by the transaction is isolated from other transactions. Most databases enforce isolation by means of locking; you should double-check what method your targeted DBMS uses. The tradeoff is between performance and concurrency—the more locks the system has to maintain, the more likely it is that there will be conflicts and slowdowns as different processes try to access the same resources.

The following is a list of the isolation levels supported in ADO.NET, taken from the .NET Framework SDK. The isolation levels are listed from least restrictive to most restrictive:

Member name

Description

Value

Unspecified

Supported by the .NET Compact Framework.

A different isolation level than the one specified is being used, but the level cannot be determined.

-1

Chaos

Supported by the .NET Compact Framework.

The pending changes from more highly isolated transactions cannot be overwritten.

16

ReadUncommitted

Supported by the .NET Compact Framework.

A dirty read is possible, meaning that no shared locks are issued and no exclusive locks are honored.

256

ReadCommitted

Supported by the .NET Compact Framework.

Shared locks are held while the data is being read to avoid dirty reads, but the data can be changed before the end of the transaction, resulting in non-repeatable reads or phantom data.

4096

RepeatableRead

Supported by the .NET Compact Framework.

Locks are placed on all data that is used in a query, preventing other users from updating the data. Prevents non-repeatable reads but phantom rows are still possible.

65536

Serializable

Supported by the .NET Compact Framework.

A range lock is placed on the data set, preventing other users from updating or inserting rows into the dataset until the transaction is complete.

1048576

Note:   The Chaos isolation level is not supported by SQL Server or Oracle, and only the OLE DB data provider will accept it as a valid isolation level to set on a transaction. Attempting to set it for the SQL Server or Oracle provider will kick up an ArgumentException indicating an invalid IsolationLevel parameter.

The SQL Server, Oracle, and OLE DB data providers all default to the ReadCommitted isolation level. The ODBC data provider isolation level default varies, depending on the ODBC driver used. If you think ReadCommitted will not provide the isolation level you want for a given transaction, you can use the Transaction.IsolationLevel property to specify a different level. You should think very carefully about changing this setting, though, and perform adequate testing to ensure that the change gives you the behavior that you want without negative side effects like data inconsistency on one hand or concurrency issues on the other. If you have a database administrator, you should definitely consult with her about the appropriate level to use for a given task. You should also consult your database documentation to see exactly how your target database handles isolation levels and locking.

Partial Rollbacks

Occasionally you'll find a situation where you want to rollback some but not all of a transaction if an error arises. Generally you'll want to do this only when you expect the process to complete successfully the great majority of the time, and checking for success conditions for some part of it beforehand would be expensive. You are balancing the cost of doing the data modification and then having to do a rollback some small percentage of the time against the benefit of avoiding the expense of the verification routine all of the time.

Partial rollbacks are usually implemented by using either savepoints or nested transactions, depending on the database you are working with. Some DBMSs don't offer either mechanism, so consult your database documentation to see whether and how partial rollbacks are implemented.

SQL Server and Oracle allow the use of named savepoints that you can refer to when issuing a rollback, to stop the rollback at a predetermined point. They do not permit true nested transactions, which some other DBMSs use to accomplish the same task. SQL Server allows nested transactions in the simplest sense, in that you can nest BEGIN…COMMIT blocks in T-SQL. However, only the outer COMMIT will actually commit all of the transactions; the inner COMMITs only decrement a system variable so you can keep track of how many open transactions you have.

Some databases do permit true nested transactions. For these types of databases, inner COMMITs will actually commit the corresponding transaction, and even if the outer transaction is rolled back the inner one will remain committed.

Transactions with ADO.NET

ADO.NET supports two transaction models, which are defined in the .NET Framework docs as manual and automatic. Manual transactions map to what are commonly known as local or database transactions, which affect operations targeting a single database. A class can provide manual transactions by using the transaction classes and methods provided by ADO.NET to explicitly define transaction boundaries. I'll focus on manual (database) transactions in the following sections.

Automatic transactions are also available, to enable a class to enlist and participate in a distributed transaction that coordinates changes across multiple data sources. The transaction itself in such a case is handled externally, for example by COM+ and the Distributed Transaction Manager (DTC). To learn more about automatic transactions, see Automatic Transactions.

Note:   You should also be aware of the default database transaction behavior when none is specified in your code. For example, SQL Server defaults to autocommit mode, where each Transact-SQL statement is either committed (if successful) or rolled back (if not) as soon as it completes. Knowing what type of default behavior to expect from the data source you are working with can help you determine whether you need to define transactions explicitly, and also can be more generally helpful in understanding your system's behavior.

An Overview of the Transaction-Related Classes

The ADO.NET data providers offer transaction functionality through the Connection, Command, and Transaction classes. A typical transaction would follow a process similar to this:

1.                  Open the transaction using Connection.BeginTransaction().

2.                  Enlist statements or stored procedure calls in the transaction by setting the Command.Transaction property of the Command objects associated with them.

3.                  Depending on the provider, optionally use Transaction.Save() or Transaction.Begin() to create a savepoint or a nested transaction to enable a partial rollback.

4.                  Commit or roll back the transaction using Transaction.Commit() or Transaction.Rollback().

All of the data providers offer the same basic structure for handling transactions—begin the transaction off of the connection, enlist the commands, use the Transaction object to commit or rollback—but with some slight tweaks in each case to correspond with the functionality offered by the databases they target.

SQL Server Transactions

The SQL Server data provider provides transaction functionality through the following classes and members:

Class

Member

Function

SqlConnection

BeginTransaction

Open a new transaction.

SqlCommand

Transaction

Enlist the command associated with the object in an open transaction.

SqlTransaction

Save

Create a savepoint to enable a partial rollback.

SqlTransaction

Rollback

Roll back a transaction.

SqlTransaction

Commit

Commit a Transaction

The SQL Server data provider (and the OLE DB Provider for SQL Server as well) does not provide a way to construct nested transactions in code, since nested transactions are not truly supported in SQL Server, as discussed in the "Partial Rollbacks" section above. Therefore there is only one way of beginning a transaction in SqlClient—using SqlConnection.BeginTransaction(). You cannot open another transaction on the same connection until the prior one has been committed or rolled back, so there is always only one open transaction per connection at any given time. To partially roll back a transaction, use SqlTransaction.Save().

OLE DB Transactions

The OLE DB data provider provides transaction functionality through the following classes and members:

Class

Member

Function

OleDbConnection

BeginTransaction

Open a new transaction.

OleDbCommand

Transaction

Enlist the command associated with the object in an open transaction.

OleDbTransaction

Begin

Create a nested transaction, to enable a partial rollback.

OleDbTransaction

Rollback

Roll back a transaction.

OleDbTransaction

Commit

Commit a Transaction

The OLE DB data provider does not offer any way to set savepoints, but instead has a Begin() method on the OleDbTransaction object. This allows you to create nested transactions (provided they are supported by your targeted database) to provide similar functionality. In this case, you can have multiple transactions open on a single connection, and you must remember to explicitly commit or rollback each one.

Keep in mind that the behavior of the nested transactions with the .NET OLE DB data provider will depend on the behavior of both your target database and the OLE DB provider that you specify. Nested transactions must be supported by both in order to be successfully implemented.

Oracle Transactions

The Oracle data provider provides transaction functionality through the following classes and members:

Class

Member

Function

OracleConnection

BeginTransaction

Open a new transaction.

OracleCommand

Transaction

Enlist the command associated with the object in an open transaction.

OracleTransaction

Rollback

Roll back a transaction.

OracleTransaction

Commit

Commit a Transaction

The Oracle provider does not allow you to specify either savepoints or nested transactions. Savepoints are supported in Oracle, but you cannot implement them in code using the current version of the Oracle data provider. Transactions against an Oracle database must either rollback or commit completely; partial rollbacks are not an enabled scenario.

Implementing Transactions

Now that we've reviewed what classes and members are involved, let's take a look at a basic implementation. The following code illustrates a simple scenario; using a transaction to ensure that two stored procedures—one that removes inventory from a table, and one that adds inventory to another—execute together or not at all:

using System;
        
using System.Drawing;
        
using System.Collections;
        
using System.ComponentModel;
        
using System.Windows.Forms;
        
using System.Data;
        
using System.Data.SqlClient;
        
using System.Data.SqlTypes;
        
 
        
…public void SPTransaction(int partID, int numberMoved, int siteID)
        
{
        
   // Create and open the connection.
        
   SqlConnection conn = new SqlConnection();
        
   string connString = "Server=SqlInstance;Database=Test;"
        
      + "Integrated Security=SSPI";
        
   conn.ConnectionString = connString;
        
   conn.Open();
        
 
        
   // Create the commands and related parameters.
        
   // cmdDebit debits inventory from the WarehouseInventory 
        
   // table by calling the DebitWarehouseInventory 
        
   // stored procedure.
        
   SqlCommand cmdDebit = 
        
      new SqlCommand("DebitWarehouseInventory", conn);
        
   cmdDebit.CommandType = CommandType.StoredProcedure;
        
   cmdDebit.Parameters.Add("@PartID", SqlDbType.Int, 0, "PartID");
        
   cmdDebit.Parameters["@PartID"].Direction = 
        
      ParameterDirection.Input;
        
   cmdDebit.Parameters.Add("@Debit", SqlDbType.Int, 0, "Quantity");
        
   cmdDebit.Parameters["@Debit"].Direction = 
        
ParameterDirection.Input;
        
 
        
   // cmdCredit adds inventory to the SiteInventory 
        
   // table by calling the CreditSiteInventory 
        
   // stored procedure.
        
   SqlCommand cmdCredit = 
        
new SqlCommand("CreditSiteInventory", conn);
        
   cmdCredit.CommandType = CommandType.StoredProcedure;
        
   cmdCredit.Parameters.Add("@PartID", SqlDbType.Int, 0, "PartID");
        
   cmdCredit.Parameters["@PartID"].Direction = 
        
ParameterDirection.Input;
        
   cmdCredit.Parameters.Add
        
("@Credit", SqlDbType.Int, 0, "Quantity");
        
   cmdCredit.Parameters["@Credit"].Direction = 
        
ParameterDirection.Input;
        
   cmdCredit.Parameters.Add("@SiteID", SqlDbType.Int, 0, "SiteID");
        
   cmdCredit.Parameters["@SiteID"].Direction = 
        
ParameterDirection.Input;
        
 
        
   // Begin the transaction and enlist the commands.
        
   SqlTransaction tran = conn.BeginTransaction();
        
   cmdDebit.Transaction = tran;
        
   cmdCredit.Transaction  = tran;
        
 
        
   try
        
   {
        
      // Execute the commands.
        
      cmdDebit.Parameters["@PartID"].Value = partID;
        
      cmdDebit.Parameters["@Debit"].Value = numberMoved;
        
      cmdDebit.ExecuteNonQuery();
        
 
        
      cmdCredit.Parameters["@PartID"].Value = partID;
        
      cmdCredit.Parameters["@Credit"].Value = numberMoved;
        
      cmdCredit.Parameters["@SiteID"].Value = siteID;
        
      cmdCredit.ExecuteNonQuery();
        
 
        
      // Commit the transaction.
        
      tran.Commit();
        
   }
        
   catch(SqlException ex)
        
   {
        
      // Roll back the transaction.
        
      tran.Rollback();
        
 
        
      // Additional error handling if needed.
        
   }
        
   finally
        
   {
        
      // Close the connection.
        
conn.Close();
        
   }
        
}
        

As you can see, a nice way to handle transactions in .NET code is to put the Commit() in a try block, using Rollback() in a catch block to undo the changes in case of error.

Using Transactions with a DataAdapter

It is also easy to implement transactions so that they can be used with a DataAdapter.Update() call, whether you choose to create your INSERT/UPDATE/DELETE statements manually or use a CommandBuilder. You just need to set the Command.Transaction property to the appropriate Transaction object:

using System;
        
using System.Drawing;
        
using System.Collections;
        
using System.ComponentModel;
        
using System.Windows.Forms;
        
using System.Data;
        
using System.Data.SqlClient;
        
using System.Data.SqlTypes;
        
 
        
…public void CBTransaction()
        
{
        
   // Create and open the connection.
        
   SqlConnection conn = new SqlConnection();
        
   string connString = "Server= SqlInstance;Database=Test;"
        
      + "Integrated Security=SSPI";
        
   conn.ConnectionString = connString;
        
   conn.Open();
        
         
        
   // Create the DataAdapters.
        
   string cmdString = "Select WIID, PartID, Quantity "
        
      + "from WarehouseInventory";
        
   SqlDataAdapter daWarehouse = 
        
      new SqlDataAdapter(cmdString,conn);
        
 
        
   cmdString = "Select SiteID, PartID, Quantity "
        
      + "from SiteInventory";
        
   SqlDataAdapter daSite = 
        
      new SqlDataAdapter(cmdString,conn);
        
 
        
   // Create the DataSet.
        
   DataSet ds = new DataSet();
        
 
        
   // Create the CommandBuilders and generate
        
   // the INSERT/UPDATE/DELETE commands.
        
   SqlCommandBuilder cbWarehouse = 
        
      new SqlCommandBuilder(daWarehouse);
        
   SqlCommand warehouseDelete = cbWarehouse.GetDeleteCommand();
        
   SqlCommand warehouseInsert = cbWarehouse.GetInsertCommand();
        
   SqlCommand warehouseUpdate = cbWarehouse.GetUpdateCommand();
        
 
        
   SqlCommandBuilder cbSite = new SqlCommandBuilder(daSite);
        
   SqlCommand siteDelete = cbSite.GetDeleteCommand();
        
   SqlCommand siteInsert = cbSite.GetInsertCommand();
        
   SqlCommand siteUpdate = cbSite.GetUpdateCommand();
        
 
        
   // Fill the DataSet.
        
   daWarehouse.Fill(ds, "WarehouseInventory");
        
   daSite.Fill(ds, "SiteInventory");
        
 
        
   // Begin the transaction and enlist the commands.
        
   SqlTransaction tran = conn.BeginTransaction();
        
   warehouseDelete.Transaction = tran;
        
   warehouseInsert.Transaction = tran;
        
   warehouseUpdate.Transaction = tran;
        
   siteDelete.Transaction = tran;
        
   siteInsert.Transaction = tran;
        
   siteUpdate.Transaction = tran;
        
 
        
   // Modify data to move inventory
        
   // from WarehouseInventory to SiteInventory.
        
            
        
   try
        
   {
        
      //Execute the commands
        
      daWarehouse.Update(ds, "WarehouseInventory");
        
      daSite.Update(ds, "SiteInventory");
        
 
        
      //Commit the transaction
        
      tran.Commit();
        
   }
        
   catch(SqlException ex)
        
   {
        
      //Roll back the transaction.
        
      tran.Rollback();
        
 
        
      //Additional error handling if needed.
        
   }
        
   finally
        
   {
        
      // Close the connection.
        
      conn.Close();
        
   }
        
}
        
Using Savepoints

When using savepoints, it is important to remember that simply rolling back to the savepoint isn't enough. The transaction must still be committed after it is partially rolled back. Also, it is important to plan for how you will notify the user or otherwise handle partially completed transactions if you choose to implement them.

The following code sample illustrates a scenario where you are creating a new customer, and also handling the customer's request for some materials that your company provides. Let's say that you have to perform this operation over a slow connection, or for some other reason the cost of checking the inventory levels prior to the operation is prohibitive. 99.9% of the time, the whole process should complete successfully. However, if the request for materials violates a constraint that maintains minimum inventory levels in the SiteInventory table, it will fail. In that case, the outer catch block will partially roll back and then commit the transaction, thereby saving the new customer record. The inventory issue and the request for materials will then need to be handled in some way. The nested catch block rolls back the whole transaction if for some reason the partial rollback and commit sequence fails.

using System;
        
using System.Drawing;
        
using System.Collections;
        
using System.ComponentModel;
        
using System.Windows.Forms;
        
using System.Data;
        
using System.Data.SqlClient;
        
using System.Data.SqlTypes;
        
 
        
…public void SavepointTransaction()
        
{
        
   // Create and open the connection.
        
   SqlConnection conn = new SqlConnection();
        
   string connString = "Server= SqlInstance;Database=Test;"
        
      + "Integrated Security=SSPI";
        
   conn.ConnectionString = connString;
        
   conn.Open();
        
 
        
   // Create the commands.
        
   // cmdInsertCustomer creates a new customer record 
        
   // by calling the DebitWarehouseInventory 
        
   // stored procedure.
        
   SqlCommand cmdInsertCustomer = 
        
      new SqlCommand("CreateCustomer", conn);
        
   cmdInsertCustomer.CommandType = CommandType.StoredProcedure;
        
   cmdInsertCustomer.Parameters.Add
        
      ("@FirstName", SqlDbType.NVarChar, 50, "FirstName");
        
   cmdInsertCustomer.Parameters.Add
        
      ("@LastName", SqlDbType.NVarChar, 50, "LastName");
        
   cmdInsertCustomer.Parameters.Add
        
      ("@Email", SqlDbType.NVarChar, 50, "Email");
        
   cmdInsertCustomer.Parameters.Add("@CID", SqlDbType.Int, 0);
        
   cmdInsertCustomer.Parameters["@FirstName"].Direction = 
        
      ParameterDirection.Input;
        
   cmdInsertCustomer.Parameters["@LastName"].Direction = 
        
      ParameterDirection.Input;
        
   cmdInsertCustomer.Parameters["@Email"].Direction = 
        
      ParameterDirection.Input;
        
   cmdInsertCustomer.Parameters["@CID"].Direction = 
        
      ParameterDirection.Output;
        
 
        
   // cmdRequestMaterials creates a pick list
        
   // of the materials requested by the customer
        
   // by calling the InsertMaterialsRequest 
        
   // stored procedure.
        
   SqlCommand cmdRequestMaterials = 
        
      new SqlCommand("InsertMaterialsRequest", conn);
        
   cmdRequestMaterials.CommandType = CommandType.StoredProcedure;
        
   cmdRequestMaterials.Parameters.Add
        
      ("@CustomerID", SqlDbType.Int, 0, "CustomerId");
        
   cmdRequestMaterials.Parameters.Add
        
      ("@RequestPartID", SqlDbType.Int, 0, "PartId");
        
   cmdRequestMaterials.Parameters.Add
        
      ("@Number", SqlDbType.Int, 0, "NumberRequested");
        
   cmdRequestMaterials.Parameters["@CustomerID"].Direction = 
        
      ParameterDirection.Input;
        
   cmdRequestMaterials.Parameters["@RequestPartID"].Direction = 
        
      ParameterDirection.Input;
        
   cmdRequestMaterials.Parameters["@Number"].Direction = 
        
      ParameterDirection.Input;
        
 
        
   // cmdUpdateSite debits the requested materials
        
   // from the inventory of those available by calling
        
   // the UpdateSiteInventory stored procedure.
        
   SqlCommand cmdUpdateSite = 
        
      new SqlCommand("UpdateSiteInventory", conn);
        
   cmdUpdateSite.CommandType = CommandType.StoredProcedure;
        
   cmdUpdateSite.Parameters.Add
        
      ("@SiteID", SqlDbType.Int, 0, "SiteID");
        
   cmdUpdateSite.Parameters.Add
        
      ("@SitePartID", SqlDbType.Int, 0, "PartId");
        
   cmdUpdateSite.Parameters.Add
        
      ("@Debit", SqlDbType.Int, 0, "Debit");
        
   cmdUpdateSite.Parameters["@SiteID"].Direction = 
        
      ParameterDirection.Input;
        
   cmdUpdateSite.Parameters["@SitePartID"].Direction = 
        
      ParameterDirection.Input;
        
   cmdUpdateSite.Parameters["@Debit"].Direction = 
        
      ParameterDirection.Input;
        
         
        
   // Begin the transaction and enlist the commands.
        
   SqlTransaction tran = conn.BeginTransaction();
        
   cmdInsertCustomer.Transaction = tran;
        
   cmdUpdateSite.Transaction  = tran;
        
   cmdRequestMaterials.Transaction  = tran;
        
 
        
   try
        
   {
        
      // Execute the commands.
        
      cmdInsertCustomer.Parameters["@FirstName"].Value
        
         = "Mads";
        
      cmdInsertCustomer.Parameters["@LastName"].Value
        
         = "Nygaard";
        
      cmdInsertCustomer.Parameters["@Email"].Value
        
         = "MadsN@AdventureWorks.com";
        
      cmdInsertCustomer.ExecuteNonQuery();
        
 
        
      tran.Save("Customer");
        
 
        
      cmdRequestMaterials.Parameters["@CustomerID"].Value
        
         = cmdInsertCustomer.Parameters["@CID"].Value;
        
      cmdRequestMaterials.Parameters["@RequestPartID"].Value
        
         = 3;
        
      cmdRequestMaterials.Parameters["@Number"].Value
        
         = 22;
        
      cmdRequestMaterials.ExecuteNonQuery();
        
 
        
      cmdUpdateSite.Parameters["@SitePartID"].Value
        
         = 3;
        
      cmdUpdateSite.Parameters["@Debit"].Value
        
         = 22;
        
      cmdUpdateSite.Parameters["@SiteID"].Value
        
         = 4;
        
      cmdUpdateSite.ExecuteNonQuery();
        
 
        
      // Commit the transaction.
        
      tran.Commit();
        
 
        
   }
        
   catch(SqlException sqlEx)
        
   {
        
      try
        
      {
        
         // Roll back the transaction
        
         // to the savepoint.
        
         Console.WriteLine(sqlEx.Message);
        
         tran.Rollback("Customer");
        
         tran.Commit();
        
 
        
         // Add code to notify user or otherwise handle
        
         // the fact that the procedure was only 
        
         // partially successful.
        
      }
        
      catch(SqlException ex)
        
      {
        
         // If the partial rollback fails,
        
         // roll back the whole transaction.
        
         Console.WriteLine(ex.Message);
        
         tran.Rollback();
        
 
        
         // Additional error handling if needed.
        
      }
        
   }
        
   finally
        
   {
        
      // Close the connection.
        
      conn.Close();
        
   }
        
}
        
Using Nested Transactions

Nested transactions require the same considerations as savepoints, as far as making sure any partial rollbacks still commit, and handling any partially completed processes.

The following code sample illustrates a scenario where you are creating a new order, and also creating a pick list for selection of the ordered items from the warehouse. If the creation of the pick list fails—maybe the PartID is invalid for the selected location—you still want the order to be entered, and then have the pick list generated in some other fashion. The nested try/catch block encapsulates the nested transaction for the pick list processing, permitting this inner transaction to commit or fail independent of the outer transaction. The outer catch block rolls back the whole transaction if the order creation process fails.

using System;
        
using System.Drawing;
        
using System.Collections;
        
using System.ComponentModel;
        
using System.Windows.Forms;
        
using System.Data;
        
using System.Data.OleDb;
        
using System.Text;
        
…public void NestedTransaction(string UID, string pwd)
        
{
        
   // Create and open the connection.
        
   OleDbConnection conn = new OleDbConnection();
        
   StringBuilder sb = new StringBuilder();
        
   sb.Append("Jet OLEDB:System database=");
        
            sb.Append(@"C:/Databases/system.mdw;");
        
            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();
        
   }
        
}
        

Note:   The Jet provider is the only Microsoft OLE DB provider that supports nested transactions.

Conclusion

Transactions are a powerful way to ensure that data modification tasks get handled appropriately, and ADO.NET gives you the ability to easily implement them in your data access code. Think about them when you are building your data access solution and use them where necessary, and you'll help ensure the integrity of the data you work with.

 

 

西汉BC60年世界历史地图矢量文件SHP格式.zip 本资源为《西汉BC60年世界历史地图矢量文件SHP格式》压缩包,文件大小约 2.23 MB,便于集中下载、整理和使用。具体内容请结合压缩包内的实际文件与说明查看。 在当前可读取的目录中,可见属性表(.dbf)、投影说明文件(.prj)、Shapefile 主文件(.shp)、Shapefile 索引(.shx)。建议解压后保持原有目录结构,先浏览文件清单与说明,再选择需要的资料进行加载或整理。 应用方面,可根据实际资料用于学习练习、资料检索、研究整理或项目参考。使用时可先确定所需内容,建立清晰的文件分类,再按项目要求进行筛选、转换与汇总。 使用 Shapefile 数据时,请把实际配套的 .shp、.shx、.dbf 等文件保存在同一目录,并保持同名关联;加载后再检查坐标系与中文字段显示。如需叠加其它数据,请先统一坐标与字段口径。 数据来源、时间范围、坐标系、字段定义、精度和使用条件,请以实际文件及原始说明为准。本介绍不对文件名之外尚未核实的信息作额外承诺。 立即下载

相关推荐

西汉BC5年世界历史地图矢量文件SHP格式.zip

本资源为《西汉BC5年世界历史地图矢量文件SHP格式》压缩包,文件大小约 2.11 MB,便于集中下载、整理和使用。具体内容请结合压缩包内的实际文件与说明查看。 在当前可读取的目录中,可见属性表(.dbf)、投影说明文件(.prj)、Shapefile 主文件(.shp)、Shapefile 索引(.shx)。建议解压后保持原有目录结构,先浏览文件清单与说明,再选择需要的资料进行加载或整理。 应用方面,可根据实际资料用于学习练习、资料检索、研究整理或项目参考。使用时可先确定所需内容,建立清晰的文件分类,再按项目要求进行筛选、转换与汇总。 使用 Shapefile 数据时,请把实际配套的 .shp、.shx、.dbf 等文件保存在同一目录,并保持同名关联;加载后再检查坐标系与中文字段显示。如需叠加其它数据,请先统一坐标与字段口径。 数据来源、时间范围、坐标系、字段定义、精度和使用条件,请以实际文件及原始说明为准。本介绍不对文件名之外尚未核实的信息作额外承诺。

Savepoints In Transactions

Savepoints In TransactionsYou can declare intermediate markers called savepoints within the context of a transaction. Savepoints divide a long transaction into smaller parts.Using savepoints, yo

Fitzwilliam的专栏 1847

游戏开发基于Unity的四类小游戏工程化实践:2D横版闯关3D跑酷塔防解谜项目结构设计与通用模块复用

内容概要:本文系统拆解了 Unity 四类典型小游戏(2D 横版闯关、3D 跑酷、塔防、解谜)的完整项目工程,提供可复用的源码结构与核心技术实现。涵盖角色控制、关卡切换、对象池、无限地形、网格放置、A* 寻路、波次调度、状态机、事件系统、存档机制等核心模块,并统一采用“流程控制与玩法逻辑分离”的工程架构,强调数据驱动与模块解耦。每个项目均配备可运行的最小场景配置与常见问题排查清单,帮助开发者从 Demo 迈向完整项目。; 适合人群:具备 Unity 基础操作能力,正在从练习 Demo 转向开发完整项目的游戏开发者,尤其是工作 1-3 年、希望提升工程化能力的研发人员;也适合独立开发者寻找可复用的项目模板。; 使用场景及目标:①掌握从小型 Demo 到结构清晰的完整项目之间的过渡方法;②学习对象池、事件系统、数据驱动、状态机等在实际项目中的应用;③复用通用工程骨架(GameManager、AudioManager、SaveSystem、GameEvents)快速搭建新项目;④通过排查清单高效定位开发中的典型问题。; 阅读建议:建议按照“2D 横版闯关 → 3D 跑酷 → 解谜 → 塔防”的顺序逐步实践,先建立完整项目认知,再深入性能优化与系统设计;阅读时应结合代码实现与文档说明,动手调试关键逻辑(如对象池复用、场景异步加载、状态机迁移),并参考排查清单主动验证常见问题。

设置ODBC的自定义类CSetODBC

何志丹一,功能描述用于配置数据源用户名及密码.1,可以得到连接串,此串可用于CMyRecordset(派生于CRecordset)的GetDefaultConnect(),也可以用干CDataBase类OpenEx.2,如果用户配置正确,只需要配置一次,相关信息记录在文件.3,可以指定存储信息的文件名.因为有可能几个程序共用一个数据源.4,用户可以重新配置数据5,可以得到当前数据的类型.6

闻缺陷则喜何志丹 3211

问:技术转移机构引入数智化包干制服务后,如何解决科技成果与产业需求匹配不准的痛点?实际案例效果如何?.docx

问:技术转移机构引入数智化包干制服务后,如何解决科技成果与产业需求匹配不准的痛点?实际案例效果如何?

政府购买服务模式下,技术转移机构如何为军工单位提供成果转化的全流程代办?.docx

政府购买服务模式下,技术转移机构如何为军工单位提供成果转化的全流程代办?

技术转移机构在开展服务时,如何利用数字化工具提升管理效率?.docx

科易网基于行业知识库+行业大数据+科技资源要素+AI模型,以AI,赋能技术转移、成果转化、技术经理人培训、知识产权管理、区域产业分析与布局、地方科技招商、创新创业大赛等场景,推出科技创新领域的AI工具、场景化服务和数智化解决方案,推动科技创新与产业创新智能化发展。

1201091 剪切挤压切挤复合成形实用手册.pdf

技术分享,制作技术

基于RRT与贪心平滑的PUMA560机械臂避障+路径规划及运动学仿真(改进前后对比)

内容概要:本文系统研究了基于RRT(快速扩展随机树)与贪心平滑算法相结合的PUMA560六自由度机械臂避障路径规划方法,旨在解决复杂静态环境中机械臂的无碰撞路径搜索与轨迹优化问题。研究首先利用RRT算法在高维构型空间中进行高效采样与树状扩展,实现起点到目标点的初始可行路径生成;随后引入贪心平滑策略对初始路径进行后处理,通过迭代优化减少路径长度、提升运动平滑性并降低关节加速度突变,从而提高实际执行的稳定性和效率。文中完成了完整的运动学建模、正逆运动学求解、碰撞检测机制设计及仿真验证流程,并通过改进前后路径指标(如路径长度、平滑度、计算耗时)的定量对比,充分验证了所提方法在路径质量与算法性能上的优越性,为工业机器人自主规划提供了有效的技术参考。; 适合人群:具备机器人学、自动控制理论及MATLAB/Simulink仿真基础的科研人员与工程技术开发者,特别适用于从事机械臂路径规划、智能算法应用、运动控制算法开发的硕士博士研究生及自动化、智能制造领域的研发工程师。; 使用场景及目标:①实现PUMA560机械臂在存在静态障碍物的工作空间中的安全避障路径规划;②对比原始RRT算法与融合贪心平滑策略的改进算法在路径长度、平滑性与计算效率等方面的性能差异;③构建从路径生成、轨迹优化到运动学仿真的完整闭环流程,为后续实际控制指令生成与实物系统部署提供可靠的仿真依据。; 阅读建议:建议结合MATLAB平台复现算法代码,重点掌握RRT的采样机制、邻近节点选择、碰撞检测实现方式以及贪心平滑的具体迭代逻辑;同时可在此基础上拓展研究动态障碍规避、多机械臂协同规划或引入其他优化算法(如B样条拟合、遗传算法调参)以进一步提升路径性能。

国内科技成果转化服务市场:近三年增长趋势解析.docx

科易网基于行业知识库+行业大数据+科技资源要素+AI模型,以AI,赋能技术转移、成果转化、技术经理人培训、知识产权管理、区域产业分析与布局、地方科技招商、创新创业大赛等场景,推出科技创新领域的AI工具、场景化服务和数智化解决方案,推动科技创新与产业创新智能化发展。

Vibe Design Lite 是一套开源的静态网站模板:HTML、CSS、原生 JS,不依赖前端框架,无需构建 克隆或解压后,本地静态服务打开根目录,或直接双击首页 HTML 即可预览

本模板适合作为产品落地页、轻量工作台、活动专题页、以及单文件小工具初始模板,可省去从零搭建的过程,使用时按场景保留或删减即可。模板文件结构与目录分层清晰、代码与视觉规范统一,包含了各类常用组件及元素,并支持按需调用,可以快速使用 Agent 进行修改和扩展。 核心特色: 设计 Token、营销壳层、常用控件和若干营销区块已内置;顶栏可切亮暗、点选主色,偏好会本地记住。改品牌主色后整站强调色联动,说明文档里写了具体改法和注意事项。 ● 零构建:保存后用浏览器刷新即可预览 ● 复制即用:整目录复制为新站;多站并行时记得改掉主题存储键名,避免偏好互相覆盖 ● 组件与区块:按钮、表单、标签、反馈、表格等可对照橱窗接入;步骤胶囊、提示卡等可从展示页拷到业务页改文案 ● 工作台示意:附带仪表盘、列表、表单、空状态等多页样板,适合评审前示意信息结构;正式接权限与接口应对齐 Pro 等工程方案 ● 窄屏:营销页顶栏在手机上收成抽屉,主要区块按断点自适应 ● 可删减:主题色板演示、公众号弹窗、多余示范页都可去掉;说明文档里有「轻量化」删减建议 在线演示:https://www.vibepm.net/vibedesign/lite/

alyunOSS-v1.9.5

alyunOSS-v1.9.5

基于超螺旋滑模观测器的永磁同步电机无位置传感器控制仿真模型(Simulink仿真实现)

内容概要:本文介绍了基于超螺旋滑模观测器的永磁同步电机无位置传感器控制仿真模型,该模型利用Simulink平台实现,旨在通过先进的滑模观测技术精确估计电机转子的位置与速度,从而实现无位置传感器的高性能控制。文中详细阐述了超螺旋滑模观测器的设计原理及其在抑制抖振、提高观测精度方面的优势,同时涵盖了永磁同步电机的数学建模、控制系统设计、仿真参数设定及仿真结果分析等关键环节。此外,该模型能够有效应对电机参数变化和外部干扰,展现出良好的鲁棒性和动态响应特性。; 适合人群:自动化、电气工程及相关专业的研究生、科研人员以及从事电机控制技术研发的工程师。; 使用场景及目标:①为永磁同步电机无位置传感器控制技术的研究提供一个可靠的仿真平台;②促进超螺旋滑模观测器在电机控制领域的应用与发展,特别是在需要高精度、高可靠性控制的工业场合;③为相关教学与培训活动提供实例支持。; 阅读建议:建议读者在学习过程中结合理论知识与实际操作,深入理解超螺旋滑模观测器的工作机理,并尝试调整仿真参数以观察不同条件下系统的响应变化,进而加深对无位置传感器控制技术的理解与掌握。

FYZN Pcb 1.1.0.2-LITE.rar

FYZN Pcb 1.1.0.2-LITE.rar

微电网含分布式发电的微电网中储能装置容量优化配置(Matlab代码实现)

内容概要:本文围绕含分布式发电的微电网中储能装置的容量优化配置问题展开研究,旨在通过科学方法确定储能系统的最佳容量,以提升微电网的运行效率与经济性。研究综合考虑了分布式电源(如光伏、风电)的出力不确定性以及负荷波动特性,构建了以系统运行成本最小化、新能源消纳率最大化和电压稳定性提升为目标的多目标优化模型。文中采用Matlab进行仿真建模与算法实现,运用智能优化算法(如遗传算法、粒子群优化等)对模型进行求解,得到了不同场景下的最优储能配置方案,并通过仿真结果验证了所提方法的有效性与优越性。研究还探讨了储能配置对微电网削峰填谷、平抑功率波动及提高供电可靠性的积极作用。; 适合人群:具备电力系统、自动化或相关专业背景,熟悉Matlab编程,从事微电网、分布式能源、储能系统等领域研究的研究生、科研人员及工程技术人员。; 使用场景及目标:①用于微电网规划设计阶段的储能容量决策支持;②为含高比例可再生能源的配电网优化运行提供技术参考;③支撑科研项目中关于能源系统优化调度的模型构建与算法验证。; 阅读建议:建议读者结合Matlab代码深入理解模型构建与求解流程,重点关注目标函数的设计、约束条件的处理及优化算法的实现细节,同时可尝试复现仿真结果并进行参数敏感性分析,以加深对储能优化配置机制的理解。

geo源码部署无限开oem

geo系统源头支持源码部署 贴牌代理 功能如下: 1.ai自动拓词,大模型抓取行业热词,自动拓词,全方位覆盖 2.自动写高质量文章,系统对接多个大模型接口,想用那个用哪个(可自主溢价) 3.多台发布,授权多平台多账号发布,喂养ai 4.自动查询收录情况 5.官方媒体投稿,目前对接2万多家媒体,想发哪家发哪家 6.新增2种主题,方便做市场差异化,后台·自己选择 7.ai诊断,前景分析,针对单个公司和同行对比,注重做什么 8.ai建站,一键发文 9.数字人,文生图,视频混剪等功能 10.b2b网站发布,定时发布,手机号收录更稳定 11.其他功能请查看演示 12.持续更新中

技术转移管理行业白皮书:成果转化堵点与数智化破局路径.docx

科易网基于行业知识库+行业大数据+科技资源要素+AI模型,以AI,赋能技术转移、成果转化、技术经理人培训、知识产权管理、区域产业分析与布局、地方科技招商、创新创业大赛等场景,推出科技创新领域的AI工具、场景化服务和数智化解决方案,推动科技创新与产业创新智能化发展。

ESP32-S3开发板实战:5分钟搞定智能门铃的音视频通话功能(附源码)

本文详细介绍了如何利用乐鑫ESP32-S3开发板快速实现智能门铃的实时音视频通话功能。通过ESP-ADF框架和RTC服务,开发者可在五分钟内完成环境搭建与核心功能调试,并附有源码和关键配置详解,为嵌入式音视频应用开发提供了高效实践路径。

web99的专栏 540
上一篇: Retrieving the Gazoutas: Understanding SQL Server Return Codes and Output Parameters
下一篇: CallAspxPageWithDotNet
wangxi1240
博客等级 码龄25年 0粉丝 34原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值