2010-08-19 75 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