2014-12-05 27 views
2

我有一個連接到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; 
} 

回答

0

謝謝特拉維斯。

我剛剛通過使該函數成爲靜態並從數據庫連接中刪除單例模式來解決問題。我爲了節省內存而構建它,但在這種情況下,它造成了更多的問題,而不是解決問題。

0

MySql中的併發性是一場噩夢。對不起,像這樣開始,但如果它在所有可能的情況下都應該移植到MSSQL,因爲你正在使用C#並且它非常容易集成。

使用MyISAM MySQL數據庫引擎時,併發性特別差。首先,還有一個大紅旗,就是MyISAM 不支持交易。這意味着您無法更改任何讀取或更新的隔離級別。其次,與第一個相關的是,使用表上的讀取發出低級表鎖。但是,爲了進行更新,它必須具有排它表鎖,而其他任何(甚至是低級)鎖都將防止發生這種情況,並且它將進入鎖隊列。

這是沒有解決,因爲它是由設計。

相關問題