0

我收到错误:在调用 Read() 之前尝试访问字段无效:字符串结果 = Reader.GetString(0);

我不完全确定该怎么做或出了什么问题

internal int GetCharGuidByName(string charactername, MySqlConnection connection)
{
    MySqlCommand command = connection.CreateCommand();
    MySqlDataReader Reader;
    command.CommandText = "SELECT guid FROM characters WHERE name=\""+charactername+"\";";
    // Initialize MySQL Reader
    Reader = command.ExecuteReader();
    Reader.Read();
    string result = Reader.GetString(0);
    // If the character doesn't exist or isn't entered, return 0
    int charguid = 0;
    if (result != String.Empty)
    {
        charguid = Convert.ToInt32(result);
    }
    return charguid;
}
4

3 回答 3

2

将代码更改为:

Reader = command.ExecuteReader();
int charguid = 0;
if(Reader.Read())
{
   if(Reader[0] != DBNull.Value)
   {
       if(int.TryParse(Reader[0].ToString(), out charguid))
       {
        //value read and is an integer!
       }
   }
}
return charguid;
于 2012-07-13T19:19:46.073 回答
1

您应该使用 ExecuteScalar 而不是 ExecuteReader

ExecuteSaclar 返回结果集中第一行的第一列,或空引用

ExecuteReader 将作为结果集返回,您必须对其进行迭代才能读取

因此,查看您的代码,您只需要结果集的第一列

internal int GetCharGuidByName(string charactername, MySqlConnection connection)
{
    int charguid = 0;

    using(MySqlCommand command = connection.CreateCommand())
    {
      command.CommandText = "SELECT guid FROM characters WHERE name=\""+charactername+"\";";
      object obj  = command.ExecuteScalar();
      if (obj != null && obj != DBNull.Value)
      {
         charguid = Convert.ToInt32(obj);
      }
    }

      return charguid;
}
于 2012-07-13T19:48:14.383 回答
0
            openConnection()

            sql = "SELECT last, first, emp_type, active FROM employee INNER JOIN account ON employee.emp_id = account.emp_id WHERE employee.emp_id = '" & AtxtEmpID.Text & "'"

            command = New MySqlCommand(sql, mySqlConnection)

            reader = command.ExecuteReader

            reader.Read()

            AtxtEmpName.Text = reader.Item(0) & ", " & reader.Item(1)

            closeConn()

有保存问题

于 2016-03-29T05:55:02.293 回答