zoukankan      html  css  js  c++  java
  • 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;
            }
        }
    

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

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

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

  • 相关阅读:
    js高级程序设计AJAX && JSON
    python核心高级学习总结7正则表达式
    python核心高级学习总结8动态性、__slots__、生成器、迭代器、装饰、闭包
    python核心高级学习总结3python实现进程的三种方式及其区别
    python核心高级学习总结6面向对象进阶之元类
    运维术语名词
    资源分享编程、数据库、安全、运维等
    python之Bug之字符串拼接bug
    CSS hack:实现IE6、IE7、Firefox兼容(转摘)
    (装载) Web开发技术的历史发展简介
  • 原文地址:https://www.cnblogs.com/Wolfmanlq/p/5923587.html
Copyright © 2011-2022 走看看