C# 操作Mysql 開始事務 BeginTrans Nested transactions are not supported.

本文探讨了在MySQL中遇到的BeginTransNestedtransactionsarenotsupported异常,详细分析了AUTOCOMMIT参数设置对事务处理的影响,并提供了具体的代码示例来说明如何正确地使用事务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

異常提示BeginTrans Nested transactions are not supported.(即事務嵌套異常)

 檢查代碼並沒有發現嵌套事務問題,最後發現是AUTOCOMMIT參數設定問題

SET GLOBAL AUTOCOMMIT=0  時事務需要在使用sql之前(包含OpenDataTable)

SET GLOBAL AUTOCOMMIT=1 時事務可以在任何位置

try
{		
	//conn.BeginTrans();//SET GLOBAL AUTOCOMMIT=0時事務需要放在開頭
	//獲取任務單號的的表名
	DataTable Dtemp = conn.OpenDataTable("select t_name from lrtablefilter where task_no='" + TaskNo + "'", CommandType.Text);
	if (Dtemp.Rows.Count > 0)
	{
		string tableName = Dtemp.Rows[0]["t_name"].ToString();
		conn.BeginTrans();//事務放在這個地方提示事務嵌套,挪到查詢前面就沒有問題 問題由於SET GLOBAL AUTOCOMMIT=0;
		//獲取執行前最大uid ,for update 寫鎖,必須放在事務里,否則沒有意義
		Dtemp = conn.OpenDataTable("select ifnull(max(uid),0) from " + tableName, CommandType.Text);
		if (Dtemp.Rows.Count > 0)
		{
			result = Dtemp.Rows[0][0].ToString();
		}
		MultInsert(conn, DT, tableName, "from_sit", SitNo);
		//獲取執行后最大uid
		Dtemp = conn.OpenDataTable("select ifnull(max(uid),0) from " + tableName, CommandType.Text);
		if (Dtemp.Rows.Count > 0)
		{
			result += "," + Dtemp.Rows[0][0].ToString();
		}
		conn.Commit();	
	}
	Dtemp.Dispose();
	Dtemp = null;
}
catch (Exception ex)
{
	if (conn._Transaction != null)
	{
		conn.Rollback();
	}			
	throw ex;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值