我有一個連接到MySQL數據庫的C#Web應用程序。當多個用戶同時訪問該站點時,我們看到「已經有一個與此命令關聯的開放數據讀取器,必須先關閉」錯誤。只有一個人訪問該網站時,該應用程序正常工作。應用程序上的併發用戶導致MySQL數據庫錯誤
我在連接字符串中發現了多個位於MultipleActiveResultSets = True的文章,但只適用於SQL Server而不是MySql。
我將錯誤追溯到我的runSQL函數,該函數處理大量數據庫查詢,但無法找到解決方案。
這是一個相當簡單的功能,它需要原始的SQL代碼的參數列表,這相當於許多可能的數據庫連接字符串的一個枚舉,並決定,如果我們需要建立事務的布爾。
我不知所措。
public DataTable runSQL(string QueryStr, List<MySqlParameter> Parameters, ConnectionType Connection, bool Transaction)
{
DataTable results = new DataTable();
MySqlConnection con = new MySqlConnection(getConnection(Connection));
MySqlTransation trans;
MySqlCommand command;
con.Open();
//if a transaction was requested, tie one to the query
if(Transaction)
{
trans = con.BeginTransaction();
command = new MySqlCommand(QueryStr, con, trans);
}
else
{
command = new MySqlCommand(QueryStr, con);
}
//if parameters were provided add them to the query
if(Parameters.Count > 0)
foreach(MySqlParameter parm in Parameters)
command.Parameters.Add(parm);
try
{
//send the command and get the results
MySqlReader rdr = command.ExecureReader();
//populate the column names
string columnName;
Type type;
foreach(DataViewRow row in rdr.GetSchemaTable().DefaultView)
{
columnName = row["ColumnName"].ToString();
type = (Type)row["DataType"];
results.Columns.Add(columnName, type);
}
//populate the results
results.Load(rdr);
//so far so good, close the transaction if one was requested
if(Transaction)
{
command.Transaction.Commit();
}
con.Close();
}
catch (Exception up)
{
//something bad happened, rollback if there was a transaction
if(Transaction)
{
command.Transaction.Rollback();
}
con.Close();
//report the error for handling at source.
throw up;
}
return results;
}