求助,我使用SQL Server作为我的数据库,我的后端是VB.NET。
我想分配这个查询的值:
SELECT sum(productPrice) from cartTbl
到一个变量,然后将值赋给一个名为totalPrice
.
我该怎么做?先感谢您!
ExecuteScalar()
如果使用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
然后,您可以调用此方法来获取价格。
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
要扩展已经说过的内容,您可以使用以下内容使其更加灵活:
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
就这么简单,但请阅读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