MySqlConnection 并发连接的问题

时间:2024-05-12 08:06:19

最近在做项目的过程中遇到一个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.

也就是说同一时刻只允许有一个连接被打开读取数据。

* 上的分析如下:

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 并发连接的问题