C# MySQL reader 未读取
C# MySQL reader is not reading
我有一个从指定列读取值的函数。它看起来像这样:
private bool OpenConnection() // Just opens the connection. No error here.
{
try
{
conn.Open();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show("Connection not opened");
return false;
}
}
private void getStats(string user, string cate, string score)
{
if (OpenConnection())
{
try
{
string getuserstats = $"SELECT {cate} FROM scores WHERE user = '{user}'";
MySqlCommand cmd = new MySqlCommand(getuserstats, conn);
MySqlDataReader getscore = cmd.ExecuteReader();
MessageBox.Show(getscore.Read().ToString()); //outputs false.
while(getscore.Read())//does not run
{
MessageBox.Show("Reading!");//does not run
score = getscore.GetString(0);//does not run
MessageBox.Show(score); //does not run
}
getscore.Close();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error getting scores!");
conn.Close();
}
}
else
{
MessageBox.Show("Connection not opened!");
}
}
SQL 命令部分似乎 运行 很好,我用一些不同的查询对其进行了测试,它们都工作正常。
然而,SQL reader 本身似乎并不 运行。我也没有收到异常错误。
我用了一个消息框来显示我的 reader 读数的布尔值,它输出的是 false。这是为什么?
Read()
returns 错误的最可能原因是没有记录与您正在执行的查询匹配。您确定 table 中有与给定用户名匹配的记录吗?并且您要连接的数据库就是您认为它要连接的数据库。
这不会相关,但 MySqlCommand 和 MySqlDataReader 都是一次性的,连接也是如此,因此您应该将它们放在 "using" 块中,或者明确地处理它们。
我有一个从指定列读取值的函数。它看起来像这样:
private bool OpenConnection() // Just opens the connection. No error here.
{
try
{
conn.Open();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show("Connection not opened");
return false;
}
}
private void getStats(string user, string cate, string score)
{
if (OpenConnection())
{
try
{
string getuserstats = $"SELECT {cate} FROM scores WHERE user = '{user}'";
MySqlCommand cmd = new MySqlCommand(getuserstats, conn);
MySqlDataReader getscore = cmd.ExecuteReader();
MessageBox.Show(getscore.Read().ToString()); //outputs false.
while(getscore.Read())//does not run
{
MessageBox.Show("Reading!");//does not run
score = getscore.GetString(0);//does not run
MessageBox.Show(score); //does not run
}
getscore.Close();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error getting scores!");
conn.Close();
}
}
else
{
MessageBox.Show("Connection not opened!");
}
}
SQL 命令部分似乎 运行 很好,我用一些不同的查询对其进行了测试,它们都工作正常。
然而,SQL reader 本身似乎并不 运行。我也没有收到异常错误。
我用了一个消息框来显示我的 reader 读数的布尔值,它输出的是 false。这是为什么?
Read()
returns 错误的最可能原因是没有记录与您正在执行的查询匹配。您确定 table 中有与给定用户名匹配的记录吗?并且您要连接的数据库就是您认为它要连接的数据库。
这不会相关,但 MySqlCommand 和 MySqlDataReader 都是一次性的,连接也是如此,因此您应该将它们放在 "using" 块中,或者明确地处理它们。