想知道如果我正在以正确的方式进行。我正在创建一个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的静态类,我不必创建一个实例来引用它。我需要帮助来理解为什么抛出异常。
我真的发现问题是什么......在我的Config类中,我需要声明来自App.Config FIRST的设置...我只是移动了公共静态字符串StationName = ConfigurationManager.AppSettings [“StationName “];直到列表的顶部,它现在工作的很好。但是我已经开始为我的关系使用最后的声明。谢谢你的提示! – muncherelli 2010-08-09 16:37:57