Realize database transactions with Microsoft.Net (2)

zhaozj2021-02-16  48

Database transaction

Database transactions are the foundation of other transaction models. The transactions discussed in this article are implemented based on database transactions, and they are only hidden in complex or container-proprietary code for handling transactions. Different database systems have their own rules when a transaction is created. By default, SQL Server works in auto-submitted mode, and will submit immediately after each statement is executed, and the comparison is Oracle requires that you contain a submission statement. But when a statement is executed by OLEDB, it will be attached to the next submitted action. In order to make the following examples apply to Oracle, you need to remove the Begin Transion and Commit Transisting, because the two statements will be run as a separate transaction.

Advantage

l All transaction logic is included in a separate call

l Have the best performance that runs a transaction

l independently of the application

limit

l Transaction context exists only in the database call

l Database code is related to the database system

example:

CREATE Procedure Up_purchaseItem

@Customerid As Int,

@itemid Int,

@itemqty int)

AS

Declare @Orderid Int

Begin Transaction

- Update The Inventory Based on PURCHASE

Update Inventory

Set QtyInstock = QtyInstock - @itemqty

Where inventory.productId = @itemid;

IF @@ error! = 0 goto error_handler

- Insert The Order Into The Database

INSERT INTO Orders

VALUES (@customerid, @itemid, @itemqty, getdate ());

IF @@ error! = 0 goto error_handler

Set @Orderid = @@ identity

Commit transaction

Return @orderid

Error_Handler:

Rollback Transaction

Set nocount off

Return 0

Go

ADO.NET transaction

Creating an ADO.NET transaction is very simple, just a small extension of standard code. As long as you know how to use ADO.NET to access the database, then you will know. The difference is that you only need to put the code in a transaction context.

Or the original ADO.NET class library reference, introduce System.Data and System.Data.SqlClient class libraries in the class that implements transactions, in order to perform a transaction, you need to create a SQLTransation object, you can call your SqlConnection object BeginTransation () Method to create it, once you save the SQLTransation object as a local variable, you can give it a transaction property of your SQLCommand object, or use it as a parameter of the constructor to create SQLCommand. Before executing the SQLCommand action, you must call the begintransaction () method and assign the SQLCommand transaction property.

A single transaction begins, you can perform any number of SQLCommand action, as long as it belongs to the same transaction and connection. Finally, you can call SQLTransation's commit () method to submit a transaction.

The ADO.NET transaction is actually passed to the transaction context to the database layer, and if an error occurs in the transaction, the database will automatically roll back. In your error handling code, check whether the transaction object is a good habit each time you call the rollback () method. One example is when a deadlock occurs while the database is performing automatic rollback. Advantage:

l simply

l and database transactions are almost fast

l Transactions can accepted across multiple databases

l Independent in the database, the proprietary code of different databases is hidden

limit:

Transaction is on the database connection layer, so you need to manually maintain a connection during the transaction.

example:

Public Int PurchaseItem (int Customerid, Int itemid, int itemqty)

{

SqlConnection Con = NULL;

SQLTransaction TX = NULL;

Int ORDERID = 0;

Try

{

Con = New SqlConnection ("Data Source = localhost; user

ID = SA; password =; initial catalog = trans_db; ");

C.Open ();

Tx = con.begintransaction (isolationledLevel.Serializable);

String UpdateSqltext = "Update Inventory Set QtyInstock

= QtyInstock - " itemqty.totring ()

"Where inventory.productid =" itemid.tostring ();

Sqlcommand cmd = new SQLCOMMAND (UpdatesqlText, Con, TX);

cmd.executenonquery ();

// String is 2 SQL Statements: The first is the insert,

The Second Selects the Identity Column

String Insertsqltext = "Insert Into Orders Values

(" Customerid.toString () ", " itemid.toString ()

"," itemqty.toT7tring () ", getdate ()); select @@ identity";

Cmd.comMandText = INSERTSQLTEXT;

// Retrieve the Order id from the identity column

ORDERID = Convert.Toint32 (cmd.executescalar ());

cmd.dispose ();

TX.comMit ();

}

Catch (SQLEXCEPTION SQLEX)

{

// Specific catch for deadlock

IF (sqlex.number! = 1205)

{

TX.rollback ();

}

ORDERID = 0;

Throw (SQLEX);

}

Catch (Exception EX)

{

TX.rollback ();

ORDERID = 0;

Throw (ex);

}

Finally

{

TX.Dispose ();

CON.CLOSE ();

}

ASP.NET transaction

ASP.NET transactions can be said to be the easiest way in the transaction implementation of the .NET platform, you just need to add a line of code. Add an additional property in the page declaration of the ASPX, which is the transaction property, which can have the following values: Disabled, NotSupport, Support, Required, and RequiresNew, these settings, and COM , and enterprise-level services. Typically if you want to run a transaction in the page context, then set to Required. If the page contains a user control, these controls will also be included in the transaction, and the transactions exist at each place in the page.

Advantage:

l Simple implementation, no additional coding

limit:

l All code in the page is the same transaction, such transactions may be large, and maybe we need separate, small transactions

l Transaction is really web layer

example:

Aspx page

<% @ Page Transaction = "Required" Language = "C #" codebehind = "ASPNET_TRANSATION.ASPX.CS"

Inherits = "transtest.aspnet_transaction" autoeventwireup = "false"%>

ASP.NET Transaction </ Title></p> <p></ hEAD></p> <p><body ms_positioning = "gridLayout"></p> <p><form id = "ASPNET_TRANSACTION" method = "post" runat = "server"></p> <p></ form></p> <p></ body></p> <p></ html></p> <p>Aspx code behind page</p> <p>Using system;</p> <p>Using system.collections;</p> <p>Using system.componentmodel;</p> <p>Using system.data;</p> <p>Using system.data.sqlclient;</p> <p>Using system.drawing;</p> <p>Using system.Web;</p> <p>Using system.Web.SessionState;</p> <p>Using system.Web.ui;</p> <p>Using system.Web.ui.webcontrols;</p> <p>Using system.Web.ui.htmlcontrols;</p> <p>Namespace Transtest</p> <p>{</p> <p>/// Summary description for aspnet_transaction.</p> <p>Public class aspnet_transaction: system.web.ui.page</p> <p>{</p> <p>Public Int PurchaseItem (int Customerid, Int itemid, int itemqty)</p> <p>{</p> <p>SqlConnection Con = NULL;</p> <p>Int ORDERID = 0;</p> <p>Try</p> <p>{</p> <p>Con = New SqlConnection ("Data Source = localhost; user</p> <p>ID = SA; password =; initial catalog = trans_db; ");</p> <p>C.Open ();</p> <p>String updatesqltext = "Update Inventory set qtyinstock = qtyinstock-" itemqty.tostring () "where inventory.productid =" </p> <p>itemid.toString ();</p> <p>Sqlcommand cmd = new sqlcommand (updatesqltext, con);</p> <p>cmd.executenonquery ();</p> <p>String Insertsqltext = "Insert Into Orders Values</p> <p>(" Customerid.toString () ", " ItemId.tostring () ", "</p> <p> Itemqty.toString () ", getdate ()); select @@ iDentity";</p> <p>Cmd.comMandText = INSERTSQLTEXT;</p> <p>ORDERID = Convert.Toint32 (cmd.executescalar ());</p> <p>cmd.dispose ();</p> <p>}</p> <p>Catch (Exception EX)</p> <p>{</p> <p>ORDERID = 0;</p> <p>Throw (ex);</p> <p>}</p> <p>Finally</p> <p>{</p> <p>C. close ();</p> <p>}</p> <p>Return OrderId;</p> <p>}</p> <p>Private Void Page_Load (Object Sender, System.EventArgs E)</p> <p>{</p> <p>Int ORDERID = PurchaseItem (1, 1, 10);</p> <p>Response.write (ORDERID);</p> <p>}</p> <p>#Region Web Form Designer Generated Code</p> <p>...</p> <p>}</p> <p>}</p> <p>Note that these and the code of the ADO.NET transaction is basically, we just removed references to the SQLTransation object. These transactions are replaced by the declaration of the ASPX page Transaction = "Required". In transactional statistics, when the page is executed, the number of transactions will increase. After a statement fails, all statements will roll back, you will see that the transaction is canceled.</p> <p>Figure 7: Statistics for ASP.NET transactions</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-25348.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="25348" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.089</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'sGjnphTc9dAity1IK6JmAGRi2wFe_2FumxSCIcZnMN6Zs4g_2FErjhAansgJZ8D8nY0Ian2HvqMf4kthkihwS2N2kw_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>