最近在做項目的過程中遇到一個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:
這下就明白了,我們在建立連接配接的時候必須每次new出來一個連接配接對象。改造一下代碼:
public class DBConnection
{
public static MySqlConnection Conn
{
get
{
MySqlConnection connection = new MySqlConnection(ConstValue.DBConnectionString);
return connection;
}
}
public static MySqlConnection CreateConnection()
{
return Conn;
}
}
這樣就解決了并發通路的時候出現的問題了。
踩過的坑,紀錄下來就是成長。
歡迎關注微信公衆平台:上帝派來改造世界的人

如果您覺得本文對你有用,不妨幫忙點個贊,或者在評論裡給我一句贊美,小小成就都是今後繼續為大家編寫優質文章的動力!
歡迎您持續關注我的部落格:)
作者:Ken Wang
出處:http://www.cnblogs.com/Wolfmanlq/
版權所有,歡迎保留原文連結進行轉載:)