【问题标题】:Parameterized upsert command over odbc doesn´t workodbc 上的参数化 upsert 命令不起作用
【发布时间】:2021-07-20 12:50:16
【问题描述】:

我在通过 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

错误信息:“ERROR [HY000] [MySQL][ODBC 5.1 Driver][mysqld-5.7.30]Column 'products_model'不能为空”

在调试器中正确设置了参数值。

类似的方法

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

ListOfProducts 是一个字典(字符串,字符串) 从我上面的示例代码中删除了错误处理和其他内容。

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

感谢您的帮助。

【问题讨论】:

  • 试一试。反转参数插入的顺序。首先将模型参数添加到参数集合中,然后再添加替换参数
  • 参数在sql语句中出现的顺序必须与加入参数集合的顺序一致。

标签: mysql vb.net parameters odbc


【解决方案1】:

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

【讨论】:

  • 谢谢!这就解释了一切!
  • PS 你不必为 MySQL 使用 odbc 驱动程序;还有一个 .net 原生的
  • 我知道,但我在使用 mysql .net dll 的不同系统上遇到了奇怪的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-28
  • 2017-06-19
  • 2013-06-05
  • 1970-01-01
  • 2016-04-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多