2010-08-09 61 views
1

想知道如果我正在以正確的方式進行。我正在創建一個C#應用程序,從我的App.Config.xml文件加載一些變量。我將它們與我從MySQL數據庫加載的其他變量一起加載到「config」類(Config.cs)中。這是我班的樣子至今:存儲配置值

class Config 
    { 
     public static string ServerHostname = ConfigurationManager.AppSettings["ServerHostname"]; 
     public static string SoftwareVersion = "v0.1a"; 
     public static int StationID = DBConnector.GetStationID(); 
     public static string StationDescription = DBConnector.GetStationDescription(); 
     public static string StationName = ConfigurationManager.AppSettings["StationName"]; 
    } 

我使用Config.StationName從MySQL數據庫中提取的Config.StationID和Config.StationDescription像這樣DBConnector.cs:

public static int GetStationID() 
    { 
     try 
     { 
      MySqlConnection conn = new MySqlConnection(connStr); 
      conn.Open(); 
      string sql = "select station_id from station_master where station_name = @station_name limit 1"; 
      MySqlCommand cmd = new MySqlCommand(sql, conn); 
      cmd.Parameters.AddWithValue("@station_name", Config.StationName); 
      object result = cmd.ExecuteScalar(); 
      conn.Close(); 
      return Convert.ToInt32(result); 
     } 
     catch (Exception ex) 
     { 
      ErrorConnection += ex.ToString(); 
      return 0; 
     } 
    } 
    public static string GetStationDescription() 
    { 
     try 
     { 
      MySqlConnection conn = new MySqlConnection(connStr); 
      conn.Open(); 
      string sql = "select station_description from station_master where station_id = '" + Config.StationID +"' limit 1"; 
      MySqlCommand cmd = new MySqlCommand(sql, conn); 
      // cmd.Parameters.AddWithValue("@station_name", Config.StationName.ToString()); 
      object result = cmd.ExecuteScalar(); 
      conn.Close(); 
      MessageBox.Show(sql); 
      return (result.ToString()); 
     } 
     catch (Exception ex) 
     { 
      ErrorGenericDBException += ex.ToString(); 
      MessageBox.Show(ErrorGenericDBException); 
      return "Error"; 
     } 
    } 

DBConnector.GetStationID類正常工作。它返回我站的整型值。但是,當我嘗試顯示Config.StationDescription時,它會引發System.NullReferenceException的異常:對象引用未設置爲Namespace.DBConnector.GetStationDescription()上的對象的實例。

我認爲,因爲我使用Config.StationName的靜態類,我不必創建一個實例來引用它。我需要幫助來理解爲什麼拋出異常。

回答

1

對我來說,看起來你可能會混淆代碼的哪一部分存在問題。既然你說的是GetSTationDescription就是拋出,我不確定你爲什麼然後假設StationName有問題?

我想看看行object result = cmd.ExecuteScalar();,如果你在這條線上放置了一個斷點,結果是否有值?

的另一個問題是,你目前僅關閉連接如果沒有拋出異常,這將是更安全,有finally語句內conn.Close();(或使用using語句,因此你不必擔心關閉它)。

+1

我真的發現問題是什麼......在我的Config類中,我需要聲明來自App.Config FIRST的設置...我只是移動了公共靜態字符串StationName = ConfigurationManager.AppSettings [「StationName 「];直到列表的頂部,它現在工作的很好。但是我已經開始爲我的關係使用最後的聲明。謝謝你的提示! – muncherelli 2010-08-09 16:37:57