In actual projects, we often encounter the need to execute multiple SQL statements in batches to implement database transactions!
Next, we will execute multiple SQL statements in batches to implement database transactions.Code: The two methods are as follows:
-------- Method 1 -------------
/// <Summary> /// execute multiple SQL statements, implement database transactions /// </Summary> /// <Param name = "sqlstringlist"> Number of rows affected by transactions executed by Multiple SQL statements </param> /// <returns> </returns> Public static int executesqltran (string connectionstring, list <string> sqlstringlist) {using (sqlconnection conntion = new sqlconnection (connectionstring) {conntion. open (); sqlcommand cmd = new sqlcommand (); cmd. connection = conntion; sqltransaction Ts = conntion. begintransaction (); cmd. transaction = ts; try {int COUNT = 0; For (INT n = 0; n <sqlstringlist. count; n ++) {string strsql = sqlstringlist [N]; If (strsql. length> 1) {cmd. commandtext = strsql; count + = cmd. executenonquery () ;}} ts. commit (); // submit the Database Transaction return count;} catch {ts. rollback (); Return 0 ;}}}
-------------------------- method 2 -------------------------------------
/// <Summary> /// execute multiple SQL statements, implement database transactions /// </Summary> /// <Param name = "sqlstringlist"> hash table of SQL statements (the key is an SQL statement, value is the sqlparameter []) of the statement </param> Public static void executesqltran (string connectionstring, hashtable sqlstringlist) {using (sqlconnection conn = new sqlconnection (connectionstring) {Conn. open (); Using (sqltransaction trans = Conn. begintransaction () {sqlcommand cmd = new sqlcommand (); try {// loop foreach (dictionaryentry mydy in sqlstringlist) {string character text = mydy. key. tostring (); sqlparameter [] parameter = (sqlparameter []) mydy. value; preparecommand (CMD, Conn, trans, plain text, parameter); int result = cmd. executenonquery (); // The execution result of the transaction can be recorded here cmd. parameters. clear ();} trans. commit ();} catch {TRANS. rollback (); throw ;}}}}
That's easy!