好吧,我尝试使用 MySQL 连接器 6.9.5 通过 C# 从 MySQL 获取数据,但收到以下错误消息:
Error: MySql.Data.MySqlClient.MySqlException: Invalid attempt to access a field before callingRead()
at MySql.Data.MySqlClient.ResultSet.get_Item(Int32 index)
at MySql.Data.MySqlClient.MySqlDataReader.GetFieldValue(Int32 index, Boolean checkNull)
at MySql.Data.MySqlClient.MySqlDataReader.GetString(Int32 i)
at PayrollManagementSystem.ConnectorDB.login(String username, String password) in C:\Users\Scarlet\Documents\Visual Studio 2008\Projects\PayrollManagementSystem\PayrollManagementSystem\ConnectorDB.cs:line 41
这意味着我试图在调用 Read() 方法之前访问一个字段,但我想我已经这样做了,这是我的代码:
public ModelUser login(String username, String password)
{
Console.WriteLine("username asal = " + username);
ModelUser val = null ;
connection.ConnectionString = connectionString;
try
{
command = new MySqlCommand( "SELECT user.id_data_user, user.username, user.password FROM user WHERE username = '" + username + "'" +
" AND password = '" + password + "'", connection);
MySqlDataReader reader;
connection.Open();
reader = command.ExecuteReader();
val = new ModelUser();
reader.Read(); == this is the Read() method was called
val.IDDataUser = reader.GetString(0); === error at this line
val.Username = reader.GetString(1);
val.Password = reader.GetString(2);
Console.WriteLine("data_user di conDb: " + val.IDDataUser);
connection.Close();
}
catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
return val;
}
我不知道我的代码出了什么问题,这是我第一次尝试 C#,非常感谢您对我的问题的答复
Update:
我像这样改变了我的代码
if (reader.HasRows)
{
while (reader.Read())
{
val.IDDataUser = reader.GetString(0);
val.Username = reader.GetString(1);
val.Password = reader.GetString(2);
}
}
else
{
Console.WriteLine("Holy cow,she's got no rows!");
}
我的读者没有行。就像它无法从数据库获取任何数据一样。这就是日志的样子:
'PayrollManagementSystem.vshost.exe' (Managed (v2.0.50727)): Loaded 'C:\Windows\assembly\GAC_MSIL\System.Configuration\2.0.0.0__b03f5f7f11d50a3a\System.Configuration.dl
', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'PayrollManagementSystem.vshost.exe' (Managed (v2.0.50727)): Loaded 'C:\Windows\assembly\GAC_64\System.EnterpriseServices\2.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Holy cow,she's got no rows!
username:
data user:
id :
The thread '<No Name>' (0x13f0) has exited with code 0 (0x0).
最佳答案
您需要检查阅读器
是否读取了一行
使用数据读取器的最佳方法是
if(reader.HasRows)
{
while(reader.Read()) // == this is the Read() method was called
{
val.IDDataUser = reader.GetString(0); === error at this line
val.Username = reader.GetString(1);
val.Password = reader.GetString(2);
Console.WriteLine("data_user di conDb: " + val.IDDataUser);
}
}
关于c# - 在调用 Read() 之前尝试访问字段无效,但在 C# 中调用了 Read(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27604722/