第一范文网 - 专业文章范例文档资料分享平台

C 中使用ADO—NET连接SQLServer数据库

来源:用户分享 时间:2025/8/10 5:25:01 本文由loading 分享 下载这篇文档手机版
说明:文章内容仅供预览,部分内容可能不全,需要完整文档或者需要复制内容,请下载word后使用。下载word有问题请添加微信号:xxxxxxx或QQ:xxxxxx 处理(尽可能给您提供完整文档),感谢您的支持与谅解。

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 listTranSQLCmd) 23 {

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

搜索更多关于: C 中使用ADO—NET连接SQLServer数据库 的文档
C 中使用ADO—NET连接SQLServer数据库.doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
本文链接:https://www.diyifanwen.net/c1xrw96djai8qp2012imx4yj364q3d4011p0_2.html(转载请注明文章来源)
热门推荐
Copyright © 2012-2023 第一范文网 版权所有 免责声明 | 联系我们
声明 :本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载的作品侵犯了您的权利,请在一个月内通知我们,我们会及时删除。
客服QQ:xxxxxx 邮箱:xxxxxx@qq.com
渝ICP备2023013149号
Top