VB.net参数化查询不需要的' \'

时间:2015-07-01 04:52:23

标签: mysql vb.net parameterized

当我执行查询时,该参数会插入一个额外的'\'字符。

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

我收到错误消息......

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

' \'来自?

1 个答案:

答案 0 :(得分:1)

您所看到的是escape character。当您使用参数化SQL时,您不能欺骗"并且在串联命令时将代码输入到字符串中以便MySQL运行。在这种情况下,'字符是用于告诉MySQL你给它一个字符串文字的代码。但是,由于您将其作为参数的一部分传递,并将其标识为一个字符串,因此正在插入\,以便MySQL读取字符串的文字值,而不是编程说明

尝试下面的修订代码。我在Selection2上添加了一个验证检查,因为我认为在某些时候你会从用户那里得到它。

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