2010-10-07 93 views
1

我有一個長時間運行的程序,每5分鐘執行一次mySQL-Queries(定時線程)。它運行約10小時後的引發NullReferenceException用下面的堆棧跟蹤:MySqlClient.NativeDriver中的NullReferenceException

at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int32& insertedId) 
    bei MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int32& insertedId) 
    at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId) 
    at MySql.Data.MySqlClient.MySqlDataReader.NextResult() 
    at MySql.Data.MySqlClient.MySqlDataReader.Close() 
    at MySql.Data.MySqlClient.MySqlCommand.ResetReader() 
    at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior) 
    at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery() 
    at MyOwnProgram.Mysql.sendData(String sqlCommmand) 

SendData方法是以下的(lockDB的類型爲Object)

public void sendData(string sqlCommmand) { 
      try { 
       using(MySqlCommand command = connection.CreateCommand()) { 
        command.CommandTimeout = 5; 
        command.CommandText = sqlCommmand; 
        lock(lockDB) { 
         command.ExecuteNonQuery(); 
        } 
       } 
      } catch(MySqlException e) { 
       throw e; 
      } catch(Exception e) { 
       // do some logging 
      } 
     } 

呼叫時,連接被打開mySQL-Class的構造函數,並在調用析構函數或調用dispose()時進行處理。有人能告訴我我做錯了什麼嗎?

回答

2

我建議你離開的連接處理,以ADO.NET:

public void sendData(string sqlCommmand) 
{ 
    using (var con = new MySqlConnection(ConnectionString)) 
    using(var cmd = con.CreateCommand()) 
    { 
     con.Open(); 
     cmd.CommandTimeout = 5; 
     cmd.CommandText = sqlCommmand; 
     cmd.ExecuteNonQuery(); 
    } 
} 

您不再需要finally聲明。如果您需要記錄某些內容,但是確保傳播異常並且不消耗它,則可以添加try/catch

+0

當調用MySQL-Class的構造函數時,什麼反對創建連接? – 2010-10-07 07:46:57

+0

到數據庫的連接字符串。 – 2010-10-07 07:48:47

+0

你能解釋一下嗎?我的連接字符串存儲在設置文件中。連接存儲在一個類變量中,並通過connection = new MySqlConnection(Settings.Default.ConnectionString)創建; – 2010-10-07 07:55:32