MySqlConnection 并发连接的问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySqlConnection 并发连接的问题相关的知识,希望对你有一定的参考价值。
最近在做项目的过程中遇到一个mysql在并发时初始化的问题,场景是这样子的:
我在Job中设定在同一时间点启动多个操作来访问数据库更新数据,结果在创建连接的时候抛出下面的问题:
Note that while a DataReader is open, the Connection is in use exclusively by that DataReader. You cannot execute any commands for the Connection, including creating another DataReader, until the original DataReader is closed.
我创建链接的代码如下:
public class DBConnection { private static MySqlConnection _conn; public static MySqlConnection Conn { get { if (_conn == null) { MySqlConnection connection = new MySqlConnection(ConstValue.DBConnectionString); _conn = connection; } return _conn; } } public static MySqlConnection CreateConnection() { return Conn; } }
之前用Sql Server数据库连接的时候也没有出现过什么问题,后来多方查找资料发现这是MySql连接的BUG。
官网描述如下:https://bugs.mysql.com/bug.php?id=7248
MySql.Data.MySqlClient.MySqlException: There is already an open DataReader associated with this Connection which must be closed first.
也就是说同一时刻只允许有一个连接被打开读取数据。
stackoverflow 上的分析如下:
You are using the same connection for the DataReader
and the ExecuteNonQuery
. This is not supported, according to MSDN:
Note that while a DataReader is open, the Connection is in use exclusively by that DataReader. You cannot execute any commands for the Connection, including creating another DataReader, until the original DataReader is closed.
这下就明白了,我们在创建连接的时候必须每次new出来一个连接对象。改造一下代码:
public class DBConnection { public static MySqlConnection Conn { get { MySqlConnection connection = new MySqlConnection(ConstValue.DBConnectionString); return connection; } } public static MySqlConnection CreateConnection() { return Conn; } }
这样就解决了并发访问的时候出现的问题了。
踩过的坑,纪录下来就是成长。
以上是关于MySqlConnection 并发连接的问题的主要内容,如果未能解决你的问题,请参考以下文章
MySqlConnection 上的“InvalidOperationException:连接必须有效且打开”
“MySql.Data.CF”和“MySql.Data”中都存在“MySqlConnection”类型
This MySqlConnection is already in use