簡體   English   中英

將查詢的值賦予變量

[英]Giving the value of a query to a variable

幫忙,我使用SQL Server作為數據庫,后端是VB.NET。

我想分配此查詢的值:

SELECT sum(productPrice) from cartTbl

變量,然后將該值提供給名為totalPrice的文本框。

我該如何執行呢? 先感謝您!

如果使用ADO.NET,則應使用ExecuteScalar()

Public Function GetProductPrice() As Integer 
    Dim ProdPrice As Int32 = 0
    Dim sql As String = "SELECT sum(productPrice) from cartTbl" 

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

    Return ProdPrice 
End Function

然后,您可以調用此方法以獲取價格。

Dim prodPrice = GetProductPrice()

您可以使用

SELECT @var1=sum(productPrice) from cartTbl

為您的計算列使用別名

 SELECT sum(productPrice) as prod_sum
 from cartTbl

然后你可以這樣閱讀

While dr.Read()     
     totalPrice.Text = dr("prod_sum")
End While

就這么簡單,但是請閱讀ADO.NET上的一些基本信息

Using con = new SqlConnection(.....constring here ....)
Using cmd = new SqlCommand("SELECT sum(productPrice) from cartTbl", con)
   con.Open()
   Dim result = cmd.ExecuteScalar()
   Console.WriteLine(result)
End Using
End Using

要擴展已經說過的內容,可以使用以下內容使其更具靈活性:

Private Sub Test()
    'Get/set connection string
    Me.TextBox1.Text = Me.SQLExecuteScalar(ConnectionString, "SELECT sum(productPrice) FROM cartTbl")
End Sub

Public Shared Function SQLExecuteScalar(ByVal ConnectionString As String, ByVal Query As String) As String
    Dim Result As String = Nothing

    Dim Exc As Exception = Nothing

    Using Conn As New SqlClient.SqlConnection(ConnectionString)
        Try
            'Open the connection
            Conn.Open()

            'Create the SQLCommand
            Using Cmd As New SqlClient.SqlCommand(Query, Conn)
                'Create an Object to receive the result
                Dim Obj As Object = Cmd.ExecuteScalar

                If (Obj IsNot Nothing) AndAlso (Obj IsNot DBNull.Value) Then
                    'If Obj is not NULL
                    Result = Obj.ToString
                End If
            End Using

        Catch ex As Exception
            'Save error so we can (if needed) close the connection
            Exc = ex

        Finally
            'Check if connection is closed
            If Not Conn.State = ConnectionState.Closed Then
                Conn.Close()
            End If

        End Try

    End Using

    'Check if any errors where found
    If Exc IsNot Nothing Then
        Throw Exc
    End If

    Return Result
End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM