Simple Method for implementing database transactions with yourself ExecuteSQLTRAN ()

xiaoxiao2021-03-06  76

When you do a project, you need to implement the database's transaction. I feel that I use the SQLTransaction to write code. It is too much trouble, I want to summarize a generic approach to put on the data layer for multiplexing. I wrote a simple method. Method can be satisfied Demand. :)

Method of implementing two SQL statements at the same time:

public static void ExecuteSqlTran (string SQLString1, string SQLString2) {using (SqlConnection conn = new SqlConnection (strDBConnectionString)) {conn.Open (); SqlCommand cmd = new SqlCommand (); cmd.Connection = conn; SqlTransaction tx = conn.BeginTransaction (); Cmd.Transaction = TX; try {cmd.commandtext = sqlstring1; cmd.executenonQuery (); cmd.commandtext = SQLString2; cmd.executenonquery (); tx.commit ();} catch (system.data.sqlclient. SQLException E) {tx.rollback (); throw new exception (E.MESSAGE);}}}

If there are multiple SQL statements that need to be implemented in a transaction, use the following method:

///

/// Implement a database transaction method executed by multiple SQL statements /// /// SQL statement list, segmentation segmentation public static void ExecuteSqlTran (string SQLStringList) {using (OdbcConnection conn = new OdbcConnection (connectionString)) {conn.Open (); OdbcCommand cmd = new OdbcCommand (); cmd.Connection = conn; OdbcTransaction tx = conn.BeginTransaction (); cmd. Transaction = TX; try = String [] split = sqlstringlist.split (new char [] {';'}; foreach (string strsql in split) {if (strsql.trim ()! = "") {Cmd.comMandText = strsql; cmd.executenonQuery ();}} tx.commit ();} catch (system.data.odbc.odbcexception e) {tx.rollback (); throw new exception (E.MESSAGE);}}}

Although it is simple, it really saves a lot of time :)

转载请注明原文地址:https://www.9cbs.com/read-107060.html

New Post(0)