Visual Studio 2015.从字符串

时间:2017-11-07 09:56:04

标签: vb.net visual-studio-2015 string-evaluation

假设我有这段代码

Dim tab As String = "myTab"
Dim val As String = "field1"
Dim con As String = "...."
Dim qry As String 'should be: "Select * from " & tab & " where value = '" & val & "'"
Dim com As New OracleCommand (qry, con)...

还假设从数据库中检索查询字符串(即qry的值)。 我无法将qry传递给oracle命令,因为它不会被评估,即变量没有绑定到它们的值,并且字符串会逐字传递给命令,从而导致错误。 有没有办法评估字符串并将其作为VB语句执行?

1 个答案:

答案 0 :(得分:1)

使用参数非常简单,就像@muffi所说的那样。

脱离我的头顶:

    Dim tab As String = "myTab"
    Dim val As String = "field1"

    Using cmd As New OracleCommand("SELECT * FROM :table WHERE value = :value", con)
        cmd.Parameters.Add(New OracleParameter() {Direction = ParameterDirection.Input, ParameterName = "table", OracleDbType = OracleDbType.Varchar2, Value = tab})
        cmd.Parameters.Add(New OracleParameter() {Direction = ParameterDirection.Input, ParameterName = "value", OracleDbType = OracleDbType.Varchar2, Value = val})
        Using OracleDataReader reader As cmd.ExecuteReader()
            While reader.Read()
                Console.WriteLine(reader.GetString(0))
            End While
        End Using
    End Using