2013-02-13 42 views
0

我想執行mysql內循環查詢,每次得到新的結果。我面臨的問題是,循環僅在第一次成功循環,第二次說明。這意味着如果它的idcount爲5,它只會變爲1,當它進入2時,會出現錯誤。循環只循環一次,請幫忙找到解決方案C#,MySQL

無效嘗試讀取調用之前訪問一個字段()
正是在這一行 「串RESULT2 = mysqlReader5 [0]的ToString();

這將是很好的你如果你能幫助我做出這個成功的循環

Thanx提前。

for (int i = 0; i < idcount; i++) 
    { 
     connection.Open(); 

     string x = idarray[i]; 


     ImageLoop img = new ImageLoop(); 
     image[i] =img.imageloop(x); 

     MySqlCommand mysqlCmd5 = new MySqlCommand("SELECT image FROM useralbum where user_id='" + x + "' LIMIT 0,1;", connection); 

     MySqlDataReader mysqlReader5 = mysqlCmd5.ExecuteReader(); 

     while (mysqlReader5.Read()) 
     { 

     } 
     string result2 = mysqlReader5[0].ToString(); 


     image[i] = result2; 

     connection.Close(); 
    } 

回答

1

您正在訪問while循環之外的閱讀器,它應該在裏面。像:

while (mysqlReader5.Read()) 
    { 
    string result2 = mysqlReader5[0].ToString(); 
    image[i] = result2; 
    } 

此外,image[i]的任務應該在while循環內完成。

+0

價值,但那麼,爲什麼它的工作的第一環,而不是爲別人。 – 2013-02-13 05:45:46

+0

@Amalan,你怎麼說,只要你在第一次循環for循環 – Habib 2013-02-13 05:48:58

+0

到達'string result2 = mysqlReader5 [0] .ToString();'這行是爲web服務該錯誤指示了這一行中的問題。另外,當我添加斷點並檢查數組的第一個值是從數據庫中檢索的。 這是指示它「在c:\ Users \ Amalan \ Documents \ Visual Studio 2010 \ WebSites \ Amalan \ App_Code \ ArrayDetails.cs:line 156」 – 2013-02-13 05:51:55

1

你應該訪問,而塊內的值

while (mysqlReader5.Read()) 
{ 
// this block is getting executed while there are records 
} 
string result2 = mysqlReader5[0].ToString(); 

而且它會更好,如果你可以使用Using塊和轉移的循環中,這樣就避免了打開和關閉每個連接時間。

0

我認爲你需要改變你的實現....試試這個鏈接引用

http://csharp-station.com/Tutorial/AdoDotNet/Lesson04

DataReader的[0]返回第一個欄value.it不用於訪問結果的數組(對此使用數據表)。數據讀取器不返回結果數組,它只能一次讀取一個結果。所以你需要讀取while(mysqlReader5.Read())中的每個數據。我希望它有幫助!!!!

1

而不是使用的同時,首先要檢查的mysqlReader5.Read()

if (mysqlReader5.Read()) 
{ 
    string result2 = mysqlReader5[0].ToString(); 
}