2012-07-13 82 views
0

我收到錯誤: 在調用Read() at之前無效嘗試訪問字段:string result = Reader.GetString(0);在調用Read()之前訪問字段的嘗試無效()

我不完全知道該怎麼做或什麼是錯,雖然

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; 
} 
+1

你有沒有打開asigning讀者Command.ExecuteReader卻方法實施前的連接?並將Reader.Read()更改爲if(Reader.Read()){...},並且如果沒有要讀取的結果,代碼將不會進入if語句。 – 2012-07-13 19:14:40

+0

是的,連接是打開的,也試圖在這個函數內創建一個連接(不使用函數接收到的連接)並打開它,它也是一樣的 – user1071461 2012-07-13 19:16:18

回答

3

更改代碼:

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; 
+0

我得到兩個錯誤:最好的重載方法匹配'int .Parse(string,System.IFormatProvider)'有一些無效參數,參數2:不能從'out int'轉換爲'System.IFormatProvider'從此代碼 – user1071461 2012-07-13 19:25:25

+1

更改爲代碼。 – 2012-07-13 19:28:40

+0

真棒,非常感謝,它的作品^^ – user1071461 2012-07-13 19:30:35

2

您應該使用的,而不是的ExecuteReader

ExecuteSaclar returns the first column of the first row in the result set, or a null reference

ExecuteReader will return as resultset which you have to then iterate to read

的ExecuteScalar所以看着你的代碼,你只需要結果集的第一列

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; 
} 
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() 

有保存問題

相關問題