如何通过 ODBC C# 绑定参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18082840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:14:25  来源:igfitidea点击:

How to bind parameters via ODBC C#?

c#parametersodbc

提问by Emanuele Pavanello

I need to bind parameters on ODBC query from C#. This is the sample code, but VS tells me that there's one parameter missing.

我需要在来自 C# 的 ODBC 查询上绑定参数。这是示例代码,但 VS 告诉我缺少一个参数。

OdbcCommand cmd = conn.CreateCommand();

cmd.CommandText = "SELECT * FROM user WHERE id = @id";
cmd.Parameters.Add("@id", OdbcType.Int).Value = 4;
OdbcDataReader reader = cmd.ExecuteReader();

What is the syntax for binding values on ODBC?

在 ODBC 上绑定值的语法是什么?

采纳答案by Steve

Odbc cannot use named parameters. This means that the command string uses placeholders for every parameter and this placeholder is a single question mark, not the parameter name.

Odbc 不能使用命名参数。这意味着命令字符串为每个参数使用占位符,并且该占位符是一个问号,而不是参数名称。

OdbcCommand.Parameters

OdbcCommand.Parameters

Then you need to add the parameters in the collection in the same order in which they appear in the command string

然后你需要按照它们在命令字符串中出现的相同顺序添加集合中的参数

OdbcCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM [user] WHERE id = ?";
cmd.Parameters.Add("@id", OdbcType.Int).Value = 4;
OdbcDataReader reader = cmd.ExecuteReader();

You have also another problem, the USER word is a reserved keyword per MS Access Database and if you want to use that as field name or table name then it is required to enclose every reference with square brackets. I strongly suggest, if it is possible, to change that table name because you will be hit this problem very often.

您还有另一个问题,USER 字是每个 MS Access 数据库的保留关键字,如果您想将其用作字段名或表名,则需要用方括号将每个引用括起来。我强烈建议,如果可能的话,更改该表名,因为您会经常遇到这个问题。

回答by C Sharper

use "?"in place of @if you are using ODBC.

如果您使用的是 ODBC "?"@请使用代替。

Try to do as follows:

尝试执行以下操作:

OdbcCommand cmd = conn.CreateCommand();

cmd.CommandText = "SELECT * FROM user WHERE id = ?";
cmd.Parameters.Add("@id", OdbcType.Int).Value = 4;
OdbcDataReader reader = cmd.ExecuteReader();

回答by Paul Zahra

To use ODBC parameterized LIKE carry out as follows, i.e. you do not use the typical single quotes or even put the % in the CommandText (Furthermore I think perhaps the %? has a special meaning for Oracle? :

要使用 ODBC 参数化 LIKE,请执行如下操作,即您不使用典型的单引号,甚至不将 % 放在 CommandText 中(此外,我认为 %? 可能对 Oracle 有特殊含义?:

OdbcCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM [user] WHERE name LIKE ?";
cmd.Parameters.AddWithValue("@fieldName", OdbcType.NVarChar).Value = "%" + nameFilter + "%";