oracle 如何创建具有可为空值的 IDbDataParameter?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1204127/
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
how to create IDbDataParameter with null-able value?
提问by David.Chu.ca
I have add a null value to parameter list for inserting values to a table, which accepts some null values. Here is my example codes:
我在参数列表中添加了一个空值,用于将值插入到表中,该表接受一些空值。这是我的示例代码:
bool sql = true;
// ....
List<IDbDataParameter> parameters = new List<IDbDataParmeter>();
// adding values...
object objVal = 1;
parameters.Add(
sql ? new SqlParameter("@colIntA", objVal) :
new OracleParamer(":colIntA", objVal));
// this would not work, what should I add?
objVal = string.Empty;
parameters.Add(
sql ? new SqlParameter("@colIntB", objVal) :
new OracleParamer(":colIntB", objVal));
Not sure if I have use db specific DbNull value and is that also SQL or Oracle specific?
不确定我是否使用了特定于 db 的 DbNull 值,这也是特定于 SQL 或 Oracle 的吗?
回答by Matt Hamilton
You're trying to assign an empty string ('') to an int parameter there, so yeah, that's not going to work.
您正在尝试将空字符串 ('') 分配给那里的 int 参数,所以是的,这是行不通的。
To represent a database-independent null value, use DbNull.Value.
要表示与数据库无关的空值,请使用DbNull.Value。
new SqlParameter("colIntB", DbNull.Value)
(Note that I've left off the "@", which works in my experience with Sqlparameters. I'm not sure whether you can do the same with the ":" for Oracle.)
(请注意,我已经省略了“@”,它在我使用 Sqlparameters 的经验中有效。我不确定您是否可以对 Oracle 的“:”做同样的事情。)
One extra tip: Use your connection to create the command, and the command to create the parameters. That will create instances of the right class depending on the type of the underlying connection:
一个额外的提示:使用您的连接创建命令,并使用命令创建参数。这将根据基础连接的类型创建正确类的实例:
IDbConnection conn = sql ? new SqlConnection(...) : new OracleConnection(...);
// this will give you either an SqlCommand or an OracleCommand
IDbCommand cmd = conn.CreateCommand();
// this will give you either an SqlParameter or an OracleParameter
IDbDataParameter param1 = cmd.CreateParameter();
param1.ParameterName = "colIntB";
param1.Value = objVal;
cmd.Parameters.Add(param1);
回答by Rex M
Use DbNull.Value. That will work for any ADO.NET-compatible data source (both SQL and Oracle providers), as it is the responsibility of the provider to know what to do when it encounters a DbNull value.
使用 DbNull.Value。这适用于任何 ADO.NET 兼容的数据源(SQL 和 Oracle 提供程序),因为提供程序有责任知道在遇到 DbNull 值时该怎么做。