简体   繁体   中英

VB.net parameterized query unwanted '\'

When I execute the query, the parameter inserts a extra '\\' character.

Dim selection2 As String = "('US1070','US1066','US1077')"

TextBox2.Text = selection2

cmd2 = New MySqlCommand("SELECT ftransactions.refNumber,clients.companyname,coordinates.postalCode,ftransactions.number, ftransactions.`date`,ftransactions.patientName," _
            & "ftransactions.total,ftransactions.refNumber,ftransactions.taxFed,  ftransactions.taxProv,  ftransactions.taxFedLabel,  ftransactions.taxProvLabel," _
            & "clients.number,ftransactions.shippingCost,coordinates.idCountryDivision, coordinates.countryDivisionName,  ftransactions.`type`,clients.companyAlias " _
            & "FROM clients Inner Join coordinates ON clients.idCoordinate = coordinates.idCoordinate Left Join ftransactions ON clients.idClient = " _
            & "ftransactions.idClient WHERE ftransactions.refNumber IN ?selec")
        With cmd2
            .Parameters.AddWithValue("?selec", selection2)
            '     .Parameters.AddWithValue("@selec2", enddate)
        End With

I get a error message ...

Check mysql syntax to use near "(\'US1070\',\'US1066\',\'US1077\')"

Where does '\\' come from?

What you're seeing is an escape character . When you use parameterized SQL, you can't "cheat" and type code into the string for MySQL to run like you can when concatenating a command. In this case, the ' character is code used to tell MySQL you are giving it a string literal. BUT, since you are passing it as part of a parameter you identify as one string, \\ is being inserted so that MySQL reads the literal value of your string, not the programmatic instructions of it.

Try the revised code below. I added a validation check on Selection2 because I assume at some point you will be getting that from the user.

Dim Selection2() As String = {"US1070","US1066","US1077"}
If Not Selection2 Is Nothing Then
    cmd2 = New MySqlCommand
    With cmd2
        .CommandText = "SELECT ftransactions.refNumber ... WHERE ftransactions.refNumber IN ("
        'Fill in the gap in your query; we are only changing the end'
        Dim vars(UBound(Selection2)) As String
        For i As Integer = 0 to Ubound(vars)
            vars(i) = "?var" & i.ToString
            .Paramaters.AddWithValue(var(i), Selection2(i))
        Next
        .CommandText &= Join(vars, ", ") & ")"
    End With
End If

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM