mr anto
mr anto

Reputation: 25

Visual Studio 2015. execute VB code from string

suppose i have this code snippet

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)...

suppose also that the query string (ie the value of qry) is retrieved from a database. I can not pass qry to the oracle command, because it would not be evaluated, ie variables are not bound to their values, and the string is passed literally to the command, causing an error. is there a way to evaluate a string and execute it as a VB statement?

Upvotes: 0

Views: 175

Answers (1)

ɐsɹǝʌ ǝɔıʌ
ɐsɹǝʌ ǝɔıʌ

Reputation: 4512

Using parameters is so simple as @muffi said.

Off the top of my head:

    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

Upvotes: 1

Related Questions