在我在这里学习的过程中,我又一次碰到了墙。基本上,我正在从数据库中读取记录并将其分配给变量,以便以后可以在表单上使用它。以下是我正在使用的代码的片段:
public static class Configuration
{
public static string ConfigurationFile { get; set; }
public static string day_BackEnable { get; set; }
public static string Day_BackTime { get; set; }
public static string day_FileKeep { get; set; }
public static string day_NotifyIcon { get; set; }
public static string day_Error { get; set; }
static Configuration()
{
ConfigurationFile = @"C:testappcfgtestapp.sdf";
ReadConfigFile();
}
public static void Reload()
{
ReadConfigFile();
}
private static void ReadConfigFile()
{
string day_BackEnable = "";
string Day_BackTime = "";
string day_FileKeep = "";
string day_Error = "";
string day_NotifyIcon = "";
SqlCeConnection conn = null;
try
{
using (conn = new SqlCeConnection("Data Source =" + ConfigurationFile + "; Password =****"))
{
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "select * from n_BackupMain";
cmd.ExecuteNonQuery();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
day_BackEnable = (reader[9].ToString());
Day_BackTime = (reader[11].ToString());
day_FileKeep = (reader[10].ToString());
day_NotifyIcon = (reader[12].ToString());
day_Error = (reader[13].ToString());
}
reader.Close();
}
}
finally
{
conn.Close();
}
}
}
然后我只是将其调用到一个消息框中,如下所示:
MessageBox.Show(day_filekeep);
但是,当它显示时,它显示为空白,就像它没有从类中读取一样。我在读取数据库后立即尝试了一个消息框,它选择了正确的值,只是没有将其传递出去以供其他地方使用。请问我做错了什么或错过了什么。
谢谢。
问题是你已经分配了具有相同名称的类成员和局部变量。
执行此操作时,赋值将首先默认为局部变量,即 ReadConfigFile
方法中的变量。
要解决此问题,只需删除ReadConfigFile
方法中声明的变量,然后实际类上的static
成员将被填充。
下面是其工作原理的快速示例:
public class Test
{
static string test = ""; // class member
public void TestTest()
{
// if you comment the below declaration out,
// then the right "test" will be assigned
string test = ""; // local member
test = "hello"; // the local member is being assigned, not the class member
}
public void GetTest()
{
// This will print "test is: [blank]" because the class member
// "test" was never assigned to
Console.WriteLine("Test is:" + test); ;
}
}
这里有一个错误,你有 2 次:
cmd.ExecuteNonQuery(); var reader = cmd.ExecuteReader();
SqlDataReader dbReader = mySqlCommand.ExecuteReader();
如果读取器具有行值
if (dbReader.HasRows)//while(xxx) 表示更多行返回
{ 读取数据
}