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;
        }
    }

这样就解决了并发访问的时候出现的问题了。

踩过的坑,纪录下来就是成长。

 

欢迎关注微信公众平台:上帝派来改造世界的人

转载于:https://www.cnblogs.com/Wolfmanlq/p/5923587.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值