ExecuteReader,使字段变量

时间:2018-07-31 01:36:28

标签: sqldatareader

我想使数据字段成为变量,我按如下方式编写了代码。 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

如何正确检索值?谢谢!

1 个答案:

答案 0 :(得分:0)

尝试使用参数创建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