首页 > 解决方案 > odbc 上的参数化 upsert 命令不起作用

问题描述

我在 odbc 上执行参数化 upsert 命令时遇到问题。

那是 upsert 命令

Dim upsert As New OdbcCommand
upsert.Connection = connection
upsert.CommandText = "
INSERT INTO products_replacement
    (products_model, products_replacement)
VALUES
        (@products_model, @products_replacement)
ON DUPLICATE KEY UPDATE  products_replacement = @products_replacement;
"
upsert.Parameters.Add("@products_replacement", OdbcType.VarChar)
upsert.Parameters.Add("@products_model", OdbcType.VarChar)



For Each Product In ListOfProducts
upsert.Parameters.Item("@products_replacement").Value = Product.Value
upsert.Parameters.Item("@products_model").Value = Product.Key

upsert.ExecuteNonQuery()
NEXT

错误消息:“错误 [HY000] [MySQL][ODBC 5.1 驱动程序][mysqld-5.7.30]列 'products_model' 不能为空”

在调试器中,参数的值已正确设置。

像这样的东西

upsert.Commandtext = upsert.Commandtext.Replace("@products_replacement", $"'{Product.Value}'").Replace("@products_model", $"'{Product.Key}'")
upsert.ExecuteNonQuery()

ListOfProducts 是一个 Dictionary(Of String, String) 错误处理和其他内容已从我上面的示例代码中删除。

参数化查询是首选,我对 MS SQL 做同样的事情没有问题……我错过了什么?

帮助表示赞赏。

标签: mysqlvb.netparametersodbc

解决方案


ODBC 不使用命名参数

您可以在 SQL 中为它们命名,但您应该想象它们都被转换为?驱动程序并按位置处理;这个名字没有意义

这意味着您需要向 VB Command.Parameters 集合中添加与语句包含的参数一样多的参数,即使这意味着重复值 - 您不能通过在 SQL 中重复名称来重用 VB 参数。该名称在 VB 中对于索引目的仍然是半有用的:

Dim upsert As New OdbcCommand
upsert.Connection = connection
upsert.CommandText = "
INSERT INTO products_replacement
    (products_model, products_replacement)
VALUES
        (?, ?)
ON DUPLICATE KEY UPDATE  products_replacement = ?;
"
upsert.Parameters.Add("@pmod", OdbcType.VarChar)
upsert.Parameters.Add("@prep1", OdbcType.VarChar)
upsert.Parameters.Add("@prep2", OdbcType.VarChar)



For Each Product In ListOfProducts
upsert.Parameters.Item("@pmod").Value = Product.Value
upsert.Parameters.Item("@prep1").Value = Product.Key
upsert.Parameters.Item("@prep2").Value = Product.Key

upsert.ExecuteNonQuery()
NEXT

推荐阅读