如何从VB中的SQL返回数组?

时间:2019-05-24 16:50:16

标签: vb.net

我正在尝试从VB运行SQL查询,该查询返回给定日期按时间升序排列的所有唯一值(Btl)的数组。

我正在处理其他人的代码,并且正在修改一个每天仅返回一个int值的版本。 (例如'1',但我希望对其进行修改以返回'1 2 3 4')

我尝试将'Btl'变量转换为类似'Btl()'的数组,但出现错误“类型'Integer()'的值不能转换为'Integer'”的错误

    {
    'Get 'wherecl' table 
    Function GetBtl(ByVal tblRS As String, ByVal nday As Integer, ByVal sqlConn As 
 SqlConnection) As Integer
    ' Get the day's sample bottle
    Dim wherecl As String
    wherecl = "WHERE (DATEDIFF(d, { fn NOW() }, TmStamp) = " & nday & ")"
    Dim Q4 As String


    ' SQL cmd to get array of unique bottles each day 
    Q4 = "SELECT distinct BottleToSample FROM " & tblRS & " " &
wherecl &
" ORDER BY TmStamp ASC;"
    'End If


    Dim MCGQ4 As New SqlCommand(Q4, sqlConn)
    Dim Btl As Integer = MCGQ4.ExecuteScalar    'This is the bottle number
    Return Btl

End Function
 }

此版本可以编译,但不显示任何结果。

例如,我希望提供“ 1 2 3 4”

1 个答案:

答案 0 :(得分:0)

由于将读取未知数量(大概是数量)的瓶子,所以最好将数据放入List(Of Integer)中-当添加项目时List会自动扩展其容量。如果您实际上需要数组中的数据,则可以轻松完成。

使用与数据库的连接时,应打开该连接,读取数据,然后立即处理该连接。 SQL Server Connection Pooling可以提高效率。对于问题代码,我通过使用连接中的连接字符串来实现。 Using Statement负责释放非托管资源,即使出现问题也是如此。

Function GetBtl(ByVal tblRS As String, ByVal nday As Integer, ByVal sqlConn As SqlConnection) As Integer()
    Dim sampleBottles As New List(Of Integer)

    ' Get the day's sample bottles
    Dim wherecl As String = "WHERE (DATEDIFF(d, { fn NOW() }, TmStamp) = " & nday & ")"
    ' SQL cmd to get array of unique bottles each day 
    Dim Q4 As String = "SELECT distinct BottleToSample FROM " & tblRS & " " & wherecl & " ORDER BY TmStamp ASC;"

    Using conn As New SqlConnection(sqlConn.ConnectionString)
        Using MCGQ4 As New SqlCommand(Q4, conn)

            conn.Open()
            Dim rdr = MCGQ4.ExecuteReader()

            While rdr.Read()
                sampleBottles.Add(rdr.GetInt32(0))
            End While

        End Using
    End Using

    Return sampleBottles.ToArray()

End Function

此外,我注意到问题代码中有一行Dim Btl As Integer = MCGQ4.ExecuteScalar,这表明Option Strict设置为“ Off”。那是次优的条件;最好使用Option Strict On。可能需要花费一些精力来更正所有代码,但最终将消除变量类型问题。