在调用Read()之前无效尝试访问字段

时间:2012-07-13 19:09:40

标签: c# mysql

我收到错误: 在调用Read()之前无效尝试访问字段 at:string result = 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;
}

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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;
}

答案 2 :(得分: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()

有保存问题