27
28 DB_Operation.ChaosDbOprt CDO = new DB_Operation.ChaosDbOprt(); 29 CDO.Chaos_ExecuteSqlTran(Chaos_SQLCmdList, strSQL); 30 31 Console.WriteLine(\数据写入成功~\32 Console.ReadLine(); 33 }
34 catch (Exception ex) 35 {
36 Console.WriteLine(\37 Console.ReadLine(); 38 } 39 }
规范化代码如下:
1 #region 实现数据库事务的方法,实现以事务的方式将多条SQL语句同时写入数据库(其中某些语句依赖于第一条语句插入数据库后自动生成的ID)
2
3 public struct Chaos_TranSQLCmd 4 {
5 ///
6 /// 一条SQL语句,在需要添加ID的地方用\来代替
7 /// 如:INSERT INTO PT_FeeItemDetails(ID_FeeItem,ID_ExamItem) VALUES ({0},005)等
8 /// 9 public string strSQL;
10
11 ///
12 /// 标记该条SQL语句是否需要连接ID 13 /// 14 public bool bNeedID; 15 }
16 ///
17 /// 该函数用于实现以事务的方式将多条SQL语句同时写入数据库(其中某些语句依赖于第一条语句插入数据库后自动生成的ID)
18 ///
19 ///
20 ///
21 /// 22 public void Chaos_ExecuteSqlTran_InsertID(string strInsertID_SQL,string strTableName, List
24 using (SqlConnection ChaosSqlConn = new SqlConnection(strSqlConnString))
25 {
26 SqlCommand ChaosSqlCmd = new SqlCommand(); 27 ChaosSqlCmd.Connection = ChaosSqlConn;
28 ChaosSqlConn.Open();
29 SqlTransaction ChaosSqlTran = ChaosSqlConn.BeginTransaction(); 30 ChaosSqlCmd.Transaction = ChaosSqlTran; 31 32 try 33 {
34 string m_strID = \35
36 //先将数据插入User
37 ChaosSqlCmd.CommandText = strInsertID_SQL; 38 ChaosSqlCmd.ExecuteNonQuery(); 39
40 string strSQL_Tmp = string.Format(\'ID'\
41 //再获取ID
42 DataSet ds = this.ExecAdapter(strSQL_Tmp, \ds.Tables[\
44 if (dt.Rows.Count>0) 45 {
46 m_strID = dt.Rows[0][\
48 for (int i = 0; i < listTranSQLCmd.Count; i++) 49 {
50 //如果队列中的语句需要连接ID,则处理SQL语句后再执行 51 string strSQL = \
52 if (listTranSQLCmd[i].bNeedID == true) 53 {
54 strSQL = string.Format(listTranSQLCmd[i].strSQL, m_strID); 55 }
56 else 57 {
58 strSQL = listTranSQLCmd[i].strSQL; 59 } 60
61 ChaosSqlCmd.CommandText = strSQL; 62 ChaosSqlCmd.ExecuteNonQuery(); 63 }
64 } 65 else 66 {
67 //如果没有正确获取首先插入语句的ID,则回滚 68 ChaosSqlTran.Rollback();
69 throw new Exception(\产生ID语句没有成功执行,后续语句无法继续执行,已回滚~\\r\\n\
70 } 71 72
73 //全部成功执行则提交 74 ChaosSqlTran.Commit(); 75 }
76 catch (System.Data.SqlClient.SqlException Ex) 77 {
78 //发生问题则回滚
79 ChaosSqlTran.Rollback(); 80 throw new Exception(Ex.Message); 81 } 82 } 83 }
84 #endregion