私はこれについて正しい方法で進んでいるかどうか疑問に思っています。App.Config.xml ファイルからいくつかの変数をロードする C# アプリケーションを作成しています。これらを、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"];
}
DBConnector.cs で次のように、Config.StationName を使用して、MySQL データベースから Config.StationID と Config.StationDescription を取得しています。
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 クラスは正常に動作します。ステーションの int 値を返します。しかし、Config.StationDescription を表示しようとすると、System.NullReferenceException: Object reference not set to an object at Namespace.DBConnector.GetStationDescription() の例外がスローされます。
Config.StationName は static クラスを使っていたので、インスタンスを作成して参照する必要はないと思いました。なぜ例外がスローされるのかを理解するのに助けが必要です。