2011-10-11 97 views
4

我試圖獲取SQL語句的結果並將其存儲在vb中的一個整數變量「count」中,因此它可以顯示在我的網站上,向用戶顯示總的Open記錄:將SQL計數結果存儲到一個變量VB

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

任何幫助表示讚賞。

+0

如何你想這麼遠嗎?你應該創建一個SqlCommand並且調用executeScalar ... –

+0

strQuery2 =「SELECT COUNT(*)FROM [tbl_Records] WHERE [Status] ='Open'」 oRs2 =新的DbConn(strQuery2,「記錄」) –

+0

我還沒有使用過executeScalar之前,所以不知道如何使用它...現在看這個 –

回答

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 
+0

正是我需要的非常感謝這! –

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 
相關問題