在Visual Basic和SQL中遇到datareader问题

时间:2010-06-22 17:54:12

标签: sql vb.net visual-studio-2010

我正在研究我正在处理的程序的搜索功能,我发现在线教程提供了一些见解,但实际代码在修改后适合我的应用程序,不起作用。我现在得到两个不同的错误,一个告诉我“类型'System.data.sqlclient.sqldatareader'的值不能转换为'one-array array of system.data.sqlclient.sqldatareader'”而另一个错误说“没有为'公共共享函数的参数'数组'指定参数...无论如何我对此有点新鲜,这就是我到目前为止所提出的建议。

Private Sub SearchOKButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchOKButton.Click

Dim TrNum
    Dim dr As SqlDataReader()

    TrNum = Me.SearchText.Text()

   Using connection As New SqlClient.SqlConnection("Data Source=XXXXX;Initial Catalog=YYYYY;Integrated Security=True;Pooling=False;Encrypt=False"), _
    cmd As New SqlClient.SqlCommand("SELECT [YYYYY] FROM (TrackingNumber) WHERE TrackingNumber = 'TrNum'", connection)

        connection.Open()
        dr = cmd.ExecuteReader()
        While dr.AsReadOnly()
            MsgBox("TrackingNumber" + "Date")
        End While
        connection.Close()

    End Using

End Sub

3 个答案:

答案 0 :(得分:1)

这里有很多问题......

<强>编辑:

我认为TrackingNumber是您要查询的表,该表包含TrackingNumberDate列。

Dim TrNum as String = Me.SearchText.Text ' <== Text is a property, not a function

Dim connectionString as string = "Data Source=XXXXX;Initial Catalog=YYYYY;Integrated Security=True;Pooling=False;Encrypt=False"

Dim cmdText as string = "SELECT TrackingNumber, [date] " & _
                        "FROM TrackingNumber " & _
                        "WHERE TrackingNumber = @trackingNumber"

Using connection As New SqlClient.SqlConnection(connectionString)

    Dim cmd As New SqlClient.SqlCommand(cmdText, connection)

    ' assign TrNum to @trackingNumber
    cmd.Parameters.AddWithValue("@trackingNumber", TrNum)    
    connection.Open()
    dim dr as SqlDataReader = cmd.ExecuteReader()

    While dr.Read()       ' <== this is probably what you want
        MsgBox(string.Format("{0} {1}", dr("TrackingNumber"), dr("Date"))
    End While

End Using

Using语法的意思是当变量超出范围时自动关闭连接。

您应该将连接字符串保留在web.config

答案 1 :(得分:0)

我不是VB专家,但我在SCOM中做了很多这种类型的连接。我的WHILE循环如下所示:

while dr.eof <> true and dr.bof <> true
    MsgBox(dr("TrackingNumber") + dr("Date"))
    dr.movenext
wend
connection.close

您的SQL语句返回了多少行?

答案 2 :(得分:0)

您的第一条错误消息告诉您需要知道的事项:当您不应该这样做时,您正尝试创建一个DataReader数组:

Dim dr As SqlDataReader()

将其更改为:

Dim dr As SqlDataReader