[英]How do I retrieve a value from an SQL query and store it in a variable in VB.NET?
I am trying to find the max product ID and store the value in a local variable "MaxID" and return this value. 我正在尝试找到最大产品ID,并将值存储在本地变量“ MaxID”中并返回此值。 I am trying to convert the result of the query into an Integer type but I am not able to do it.
我正在尝试将查询结果转换为Integer类型,但我无法做到。 Below is the code:
下面是代码:
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())
You also should know about SqlCommand.ExecuteReader()
, SqlCommand.ExecuteNonQuery()
(for inserts/updates/deletes), and SqlDataAdapter.Fill()
. 您还应该了解
SqlCommand.ExecuteReader()
, SqlCommand.ExecuteNonQuery()
(用于插入/更新/删除)和SqlDataAdapter.Fill()
。
Where you'll still have a problem is you can't use a parameter value for the table name or column name. 您仍然会遇到问题的地方是,不能将参数值用作表名或列名。 The Sql Server engine has a "compile" step, where it has to be able to work out an execution plan, including permissions/security, at the beginning of the query, but variable names like
@table
and @field
aren't resolved until later. Sql Server引擎具有“编译”步骤,该步骤必须能够在查询开始时制定出包括权限/安全性在内的执行计划,但是直到解析
@table
和@field
类的变量名之前,后来。 It's not what actually happens, but think of it as if you had string literals in those places; 这并不是实际发生的情况,而是想像您在那些地方有字符串文字。 imagine trying to run this:
想象尝试运行此命令:
SELECT MAX('ID') FROM 'MyTable'
MAX('ID')
will always return the string value ID
, and not anything from an ID
column in any rows. MAX('ID')
将始终返回字符串值ID
, 而不返回任何行的ID
列中的任何值。 But the MyTable
part is not the correct place for a string literal, and such a query wouldn't even compile. 但是
MyTable
部分不是字符串文字的正确位置,并且这样的查询甚至无法编译。
I also see people here from time to time try to create functions like GetMaxId()
, and it's almost always misguided in the first place. 我还看到人们不时尝试创建类似
GetMaxId()
函数,并且一开始它几乎总是被误导。 If the intended use for this function is the same as what I usually see, you're setting up a major race condition issue in your application (one that probably won't show up in any testing, too). 如果此功能的预期用途与我通常看到的用途相同,那么您正在应用程序中设置一个主要的竞争条件问题(一个问题也可能不会在任何测试中出现)。 Sql Server gives you features like
identity
columns, sequences
, and the scope_identity()
function. Sql Server为您提供诸如
identity
列, sequences
和scope_identity()
函数之类的功能。 You should be using those in such a way that new IDs are resolved on the server as they are created, and only (and immediately) then returned to your application code. 您应该以这样的方式使用它们:在创建新ID时在服务器上解析新ID,并且仅(立即)将其返回到您的应用程序代码。
But that issue aside, here's a better way to structure this function: 除了这个问题,这里是构造此功能的更好方法:
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.