![](/img/trans.png)
[英]how can i store the result of the selected columns in my sql query in a variable in vb.net
[英]How do I retrieve a value from an SQL query and store it in a variable in VB.NET?
我正在尝试找到最大产品ID,并将值存储在本地变量“ MaxID”中并返回此值。 我正在尝试将查询结果转换为Integer类型,但我无法做到。 下面是代码:
Public Function GetMaxID(ByVal TableName As String, ByVal ID As String) As Integer
Dim MaxID As Integer
Dim sqlquery As SqlCommand
Dim field_name As String = ID
Dim con As SqlConnection
con = New SqlConnection()
con.ConnectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='D:\Docs Dump\Work\Srinath\SrinathDB.mdf';Integrated Security=True;Connect Timeout=30"
con.Open()
Try
sqlquery = New SqlCommand("SELECT MAX( @field ) FROM @table ", con)
sqlquery.Parameters.AddWithValue("@field", field_name)
sqlquery.Parameters.AddWithValue("@table", TableName)
MaxID = CInt(sqlquery.ToString)
con.Close()
Return MaxID
Catch ex As Exception
Return 0
Exit Function
con.Close()
End Try
End Function
End Class
MaxID = CInt(sqlquery.ExecuteScalar())
您还应该了解SqlCommand.ExecuteReader()
, SqlCommand.ExecuteNonQuery()
(用于插入/更新/删除)和SqlDataAdapter.Fill()
。
您仍然会遇到问题的地方是,不能将参数值用作表名或列名。 Sql Server引擎具有“编译”步骤,该步骤必须能够在查询开始时制定出包括权限/安全性在内的执行计划,但是直到解析@table
和@field
类的变量名之前,后来。 这并不是实际发生的情况,而是想像您在那些地方有字符串文字。 想象尝试运行此命令:
SELECT MAX('ID') FROM 'MyTable'
MAX('ID')
将始终返回字符串值ID
, 而不返回任何行的ID
列中的任何值。 但是MyTable
部分不是字符串文字的正确位置,并且这样的查询甚至无法编译。
我还看到人们不时尝试创建类似GetMaxId()
函数,并且一开始它几乎总是被误导。 如果此功能的预期用途与我通常看到的用途相同,那么您正在应用程序中设置一个主要的竞争条件问题(一个问题也可能不会在任何测试中出现)。 Sql Server为您提供诸如identity
列, sequences
和scope_identity()
函数之类的功能。 您应该以这样的方式使用它们:在创建新ID时在服务器上解析新ID,并且仅(立即)将其返回到您的应用程序代码。
除了这个问题,这里是构造此功能的更好方法:
Public Class DB
Private conString As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='D:\Docs Dump\Work\Srinath\SrinathDB.mdf';Integrated Security=True;Connect Timeout=30"
'You want a separate method per-table that already knows the table and column names
Public Function GetMyTableMaxID() As Integer
Dim sql As String = "SELECT MAX(ID) FROM MyTable"
Using con As New SqlConnection(conString), _
sqlQuery As New SqlCommand(sql, con)
'Parameters would go here.
'Do NOT use AddWithValue()! It creates performance issues.
' Instead, use an Add() overload where you provide specific type information.
'No exception handling at this level. The UI or business layers are more equipped to deal with them
con.Open()
Return CInt(sqlQuery.ExecuteScalar())
End Using
'No need to call con.Close()
'It was completely missed in the old code, but handled by the Using block here
End Function
End Class
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.