[英]Giving the value of a query to a variable
Help, I am using SQL Server as my database, and my back-end is VB.NET. 帮忙,我使用SQL Server作为数据库,后端是VB.NET。
I want to assign the value of this query: 我想分配此查询的值:
SELECT sum(productPrice) from cartTbl
to a variable, and then give the value to a textbox called totalPrice
. 变量,然后将该值提供给名为
totalPrice
的文本框。
How do I perform this? 我该如何执行呢? Thank you in advance!
先感谢您!
You should use ExecuteScalar()
if using ADO.NET 如果使用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
You can then call this method to get the Price. 然后,您可以调用此方法以获取价格。
Dim prodPrice = GetProductPrice()
您可以使用
SELECT @var1=sum(productPrice) from cartTbl
Use an alias for your calculated column 为您的计算列使用别名
SELECT sum(productPrice) as prod_sum
from cartTbl
Then you can read it like this 然后你可以这样阅读
While dr.Read()
totalPrice.Text = dr("prod_sum")
End While
It is as simple as this, but please read some basic info on ADO.NET 就这么简单,但是请阅读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
To expand on what has already been said, you could use the following to make it a little more 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.