mysql odbc select命令带参数-不工作

ndh0cuux  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(375)

拜托,有人能解释一下为什么这个代码不起作用吗?通过mysql odbc驱动程序(最新版本)连接到mysql。无法识别select命令中的参数。
我还尝试替换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
8ehkhllq

8ehkhllq1#

谢谢你的帮助。此代码已在运行:

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
cgvd09ve

cgvd09ve2#

我不是百分之百肯定,但我还是会把这个作为一个答案,因为我认为它是正确的:

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
tpxzln5u

tpxzln5u3#

上面写着:

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

更改为:

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

(我已经在@param周围加了',请记住这与围绕它的''不同)

相关问题