ExecuteReader, Make field variable

Clash Royale CLAN TAG#URR8PPPExecuteReader, Make field variable
I want to make the Data Field a variable I wrote the code as follows. The SQL works but when I try to get the returned value it returns +StrVariable+ if I remove the + then it returns Strvariable literally.
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
How do I retrieve the value correctly? Thank you!
1 Answer
1
Try creating the SQL Command with parameters
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
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.