4

Im trying to get the result of an SQL statement and store it in an integer variable "count" in vb so it can then be displayed on my website showing the user the total Open records:

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

any help appreciated.

3
  • how are you trying so far? you should create a SqlCommand and call executeScalar... Commented Oct 11, 2011 at 12:36
  • strQuery2 = "SELECT COUNT(*) FROM [tbl_Records] WHERE [Status] = 'Open'" oRs2 = New DbConn(strQuery2, "Records") Commented Oct 11, 2011 at 12:37
  • i havent used the executeScalar before so not sure how to use it...will look this up now Commented Oct 11, 2011 at 12:38

2 Answers 2

4

Try this :

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
Sign up to request clarification or add additional context in comments.

Comments

4

Make use of : 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.