向 SQL 查询的 WHERE 子句添加参数
我正在使用 ADO.NET 通过 ODBC 连接到 Oracle DB。除了使用简单的 SQL 查询绑定参数之外,一切都工作正常:
Connection.Open();
IDbCommand command = Connection.CreateCommand();
command.CommandText = "SELECT length FROM activity_type WHERE name = :name_of_activity";
var parameter = command.CreateParameter();
parameter.ParameterName = ":name_of_activity";
parameter.Value = "Short_break";
command.Parameters.Add(parameter);
int result = Convert.ToInt32(command.ExecuteScalar());
Connection.Close();
它总是返回 0 个结果(来自 ExecuteScalar() 的 null - 与读取器的结果相同)。但如果我像这样放置一个简单的 SQL 查询:command.CommandText = "SELECT length FROM Activity_type WHERE name = 'Short_break'"
它会像魅力一样工作。更重要的是,我在 INSERT INTO
子句的代码中使用了类似的结构,而且效果很好。
我错过了什么吗?
I'm using ADO.NET to connect to an Oracle DB through ODBC. Everything is working fine, besides binding parameters with a simple SQL query:
Connection.Open();
IDbCommand command = Connection.CreateCommand();
command.CommandText = "SELECT length FROM activity_type WHERE name = :name_of_activity";
var parameter = command.CreateParameter();
parameter.ParameterName = ":name_of_activity";
parameter.Value = "Short_break";
command.Parameters.Add(parameter);
int result = Convert.ToInt32(command.ExecuteScalar());
Connection.Close();
It always returns 0 results (a null from ExecuteScalar()
- the same from a reader). But if I'd put a straightforward SQL query like this: command.CommandText = "SELECT length FROM activity_type WHERE name = 'Short_break'"
it would work like a charm. Whats more, I used similar constructions all over the code for INSERT INTO
clauses, and they were OK.
Am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 的文档
OdbcCommand.Parameters
:换句话说,您的代码应该如下所示:(
请注意,您可能应该考虑使用
using
语句...否则,如果这引发异常,您将不会关闭联系。)From the docs for
OdbcCommand.Parameters
:In other words, your code should look like this:
(You should probably be considering using
using
statements, mind you... otherwise if this throws an exception, you won't be closing the connection.)根据你的描述,问题只能出在参数上。
也许存在某种奇怪的混合,例如 SQL Server 上的 varchar 和 nvarchar 之间的混合,换句话说,尝试显式设置数据类型。
From what you're describing the problem can only be in the parameter.
Maybe some kind of strange mixup like between varchar and nvarchar on SQL Server, in other words try setting the datatype explicitely.
尝试更改此行:
换句话说
,删除冒号字符
Try to change this line:
to
In other words remove colon character