帮助,我使用SQL Server作为我的数据库,我的后端是VB.NET。
我想分配此查询的值:
SELECT sum(productPrice) from cartTbl
转换为变量,然后将值提供给名为totalPrice
的文本框。
我该如何表演?提前谢谢!
答案 0 :(得分:1)
如果使用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()
答案 1 :(得分:1)
你可以使用
SELECT @var1=sum(productPrice) from cartTbl
答案 2 :(得分:1)
为计算列
使用别名 SELECT sum(productPrice) as prod_sum
from cartTbl
然后你可以像这样阅读
While dr.Read()
totalPrice.Text = dr("prod_sum")
End While
答案 3 :(得分:1)
这很简单,但请阅读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
答案 4 :(得分:1)
要扩展已经说过的内容,您可以使用以下内容使其更灵活:
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