带参数的MySQL ODBC Select命令-不起作用

时间:2018-10-27 09:48:23

标签: mysql vb.net select parameters

请问有人可以解释为什么此代码不起作用吗? 通过mysql odbc驱动程序(最新)建立与mysql的连接。 无法识别“选择”命令中的参数。

我还尝试在Select命令中替换@ param1:

Select product_id from product where model = ?

代码仍然无法正常工作。

Sub Main()

    Dim DBCONT As New Odbc.OdbcConnection
    Dim strConn As String = "DSN=MyDSN"
    DBCONT.ConnectionString = strConn
    DBCONT.Open()

    Dim cmd As New Odbc.OdbcCommand
    With cmd
        .CommandText = "SELECT product_id FROM products WHERE model = @param"
        .Connection = DBCONT
    End With

    Dim param1 As Odbc.OdbcParameter
    param1 = cmd.CreateParameter()
    With param1
        .ParameterName = "@param"
        .OdbcType = Odbc.OdbcType.VarChar
        .Size = 30
        .Value = "TESTVALUE"
    End With


    Dim reader As Odbc.OdbcDataReader
    reader = cmd.ExecuteReader

    Console.WriteLine(cmd.CommandText.ToString)
    'this line displays "Select product_id from products where model = @param"
    'instead of  "Select product_id from products where model = "TESTVALUE"..
    'WHY??

    While reader.Read
        Console.WriteLine(reader(0))
        Console.WriteLine()
    End While
    Console.ReadLine()

    DBCONT.Close()
    reader = Nothing
    cmd = Nothing

End Sub

3 个答案:

答案 0 :(得分:0)

上面写着:

".CommandText = "SELECT product_id FROM products WHERE model = @param"

将其更改为:

".CommandText = "SELECT product_id FROM products WHERE model = '@param'"

(我在@param周围加上了'',请记住,这与周围的“”不同)

答案 1 :(得分:0)

我不确定100%,但是无论如何我都会将其发布为答案,因为我认为这是正确的:

Dim cmd As New Odbc.OdbcCommand
With cmd
    .CommandText = "SELECT product_id FROM products WHERE model = :param"
    .Connection = DBCONT
End With

Dim param1 As Odbc.OdbcParameter
param1 = cmd.CreateParameter()
With param1
    .ParameterName = "param"
    .OdbcType = Odbc.OdbcType.VarChar
    .Size = 30
    .Value = "TESTVALUE"
End With

答案 2 :(得分:-1)

感谢您的帮助。该代码已经可以使用:

Sub Main()

Dim DBCONT As New Odbc.OdbcConnection
Dim strConn As String = "DSN=MyDSN"
DBCONT.ConnectionString = strConn
DBCONT.Open()

Dim cmd As New Odbc.OdbcCommand
With cmd
    .CommandText = "SELECT product_id FROM products WHERE model LIKE ?"
    //it seems it is important to add paramater right after commandtext
    .Parameters.Add("@param", OdbcType.VarChar).Value = "%" + "TESTVALUE" + "%"
    .Connection = DBCONT
End With

Dim reader As Odbc.OdbcDataReader
reader = cmd.ExecuteReader
Console.WriteLine(cmd.CommandText.ToString)
//it should display SELECT product_id FROM products WHERE model LIKE ?
While reader.Read
    Console.WriteLine(reader(0))
    Console.WriteLine()
End While
Console.ReadLine()

DBCONT.Close()
reader = Nothing
cmd = Nothing

End Sub