我想让数据字段成为一个变量,我编写了如下代码。SQL是有效的,但当我尝试获取返回值时,它会返回+StrVariable+。如果我删除了+,那么它会直接返回StrVariable。
Private Function FUNCTStrSN(StrVariable As String, StrSN As String) As String
Dim sqlConn As SqlConnection
Dim sqlComm As SqlCommand
Dim r As SqlDataReader
Dim sqlstring As String
sqlstring = "Select " + StrVariable + " FROM HistorySNUnit WHERE SN='" + StrSN + "'"
sqlConn = New SqlConnection(DBConnection) : sqlConn.Open() : sqlComm = New SqlCommand(sqlstring, sqlConn) : r = sqlComm.ExecuteReader()
While r.Read()
Dim DBSN As String = CStr(r("StrVariable"))
StrSN = DBSN
End While : r.Close() : sqlConn.Close()
FUNCTStrSN = StrSN
End Function
如何正确检索值?非常感谢。
尝试使用参数创建SQL Command
Private Function FUNCTStrSN(StrVariable As String, StrSN As String) As String
Dim sqlConn As SqlConnection
Dim sqlComm As SqlCommand
Dim r As SqlDataReader
Dim sqlstring As String
sqlstring = "Select @variable FROM HistorySNUnit WHERE SN=@value"
sqlConn = New SqlConnection(DBConnection) : sqlConn.Open() : sqlComm = New SqlCommand(sqlstring, sqlConn)
sqlComm.Parameters.AddWithValue("@variable", StrVariable)
sqlComm.Parameters.AddWithValue("@value", StrSN)
r = sqlComm.ExecuteReader()
While r.Read()
Dim DBSN As String = CStr(r(StrVariable))
StrSN = DBSN
End While : r.Close() : sqlConn.Close()
FUNCTStrSN = StrSN
End Function