2010-08-19 27 views
0

下面是代碼:當我運行在查詢分析器中查詢,它返回一個行,但是當我用同一個查詢在VB.NET,沒有行返回

Function getData(ByVal id As String) 
    Dim reader As SqlClient.SqlDataReader 
    Dim statement As String 
    Dim count As Integer 
    Dim temp As Integer 

    statement = "SELECT * FROM General WHERE accountid='" + id + "'" 
    Conn.Open() 
    Comm = New SqlClient.SqlCommand(statement, Conn) 
    reader = Comm.ExecuteReader() 
    count = reader.FieldCount 

    Dim Data(count) As String 
    If reader.HasRows Then 

     For temp = 0 To count 
      Data(temp) = (reader.Item(temp)) 
     Next temp 
    Else 
     Console.WriteLine("No rows found.") 
    End If 

    reader.Close() 
    Conn.Close() 

    Return Data 
End Function 

當我運行的代碼HasRows字段爲真,但reader.Item(temp)給出錯誤

無數據存在時無效嘗試讀取。

+2

沒有解決的問題,但你不應該這樣做DB訪問這種方式 - 在ID串聯一樣,讓你對SQL注入攻擊開放。 – 2010-08-19 03:28:55

+0

感謝解決了很多問題... @David大廳然後我應該如何訪問DB pls建議 – farkhunda 2010-08-19 03:38:46

+1

對SqlClient,SQL Inection和參數做一些研究。看看這篇文章,這是我提到的第一個谷歌命中:http://msdn.microsoft.com/en-us/library/ff648339.aspx – 2010-08-19 04:22:48

回答

3

您需要一個While reader.Read()循環。讀者從行索引-1開始; Read()將前進到第一行(當然,取回它),然後你可以處理它。

這就是爲什麼你的HasRows返回true,但你不能檢索字段 - 你還沒有定位在第一行。

您可能需要做這樣的事情:

If reader.HasRows Then 
    While reader.Read() 
    For temp = 0 To count 
     Data(temp) = (reader.Item(temp)) 
    Next temp 
    End While 
Else 
    Console.WriteLine("No rows found.") 
End If