码迷,mamicode.com
首页 > 数据库 > 详细

MySqlConnection 并发连接的问题

时间:2016-09-30 15:24:18      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

最近在做项目的过程中遇到一个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 并发连接的问题

标签:

原文地址:http://www.cnblogs.com/Wolfmanlq/p/5923587.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!