幫助,我將SQL Server用作我的數據庫,而我的後端是VB.NET。將查詢的值賦予變量
我要分配給此查詢的值:
SELECT sum(productPrice) from cartTbl
給一個變量,然後給值到一個名爲totalPrice
文本框。
我該如何執行此操作?先謝謝你!
幫助,我將SQL Server用作我的數據庫,而我的後端是VB.NET。將查詢的值賦予變量
我要分配給此查詢的值:
SELECT sum(productPrice) from cartTbl
給一個變量,然後給值到一個名爲totalPrice
文本框。
我該如何執行此操作?先謝謝你!
如果使用ADO.NET
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
您應該使用ExecuteScalar()
然後,您可以調用此方法來獲得價格。
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
讀它,它就是這麼簡單這個,但請閱讀的一些基本信息
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
爲了擴大已經取得的說,你可以使用下面的做多一點flexable:
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
太感謝你了,它的工作! –
@LorenzoSalamante,沒問題。看看這個關於如何接受答案工作的鏈接http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – christiandev