将SQL计数结果存储到变量VB中

时间:2011-10-11 12:34:35

标签: asp.net sql vb.net

我试图获取SQL语句的结果并将其存储在vb中的整数变量“count”中,以便它可以显示在我的网站上,向用户显示总开放记录:

    SELECT COUNT (recordID) FROM [tbl_Records] WHERE [Status] = 'Open'

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:4)

试试这个:

Public Function GetOpenRecordCount(ByVal connString As String) As Integer
    Dim RecordCount As Int32 = 0
    Dim sql As String = "SELECT COUNT (recordID) FROM [tbl_Records] WHERE [Status] = 'Open'"

    Using conn As New SqlConnection(connString)
        Dim cmd As New SqlCommand(sql, conn)
        Try
            conn.Open()
            RecordCount = Convert.ToInt32(cmd.ExecuteScalar())
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    End Using

    Return RecordCount
End Function

答案 1 :(得分:3)

利用:SqlCommand.ExecuteScalar Method

Dim connetionString As String = Nothing
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim sql As String = Nothing

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Select Count(*) from product"

cnn = New SqlConnection(connetionString)
Try
    cnn.Open()
    cmd = New SqlCommand(sql, cnn)
    Dim count As Int32 = Convert.ToInt32(cmd.ExecuteScalar())
    cmd.Dispose()
    cnn.Close()
    MessageBox.Show(" No. of Rows " & count)
Catch ex As Exception
    MessageBox.Show("Can not open connection ! ")
End Try