带有空字符串的 ASP.Net C# CreateParameter
在我的 ASP.net C# Web 项目中,我有一个带有参数的查询命令对象。我使用以下代码来填充参数:
DbCommand command = conn.CreateCommand();
command.CommandText = query;
DbParameter param = command.CreateParameter();
param.ParameterName = parameter;
param.DbType = DbType.String;
param.Value = value;
此代码适用于除空字符串之外的所有字符串。如果我将输入字段留空,它会将值作为“”传递。如果发生这种情况,我会收到以下异常:
ORA-01400: cannot insert NULL into (string)
有没有办法允许我将空白字符串插入数据库?
我使用 Oracle 数据库,并使用 System.Data.OracleClient 作为提供程序。
In my ASP.net C# web project I have a query command object that has parameters. I use the following code to fill the parameters:
DbCommand command = conn.CreateCommand();
command.CommandText = query;
DbParameter param = command.CreateParameter();
param.ParameterName = parameter;
param.DbType = DbType.String;
param.Value = value;
This code works for all strings except for empty ones. If I would leave an input field blank, it would pass the value as "". If this happens I receive the following exception:
ORA-01400: cannot insert NULL into (string)
Is there a way that would allow me to insert blank strings into the database?
I use an Oracle database and I'm using System.Data.OracleClient as provider.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果要插入空字符串,则必须允许 NULL 值。否则,Oracle 会默默地将空字符串转换为 NULL,并且您将得到异常。
另一种选择是插入一个带有空格
' '
的空字符串,但我认为这会很痛苦。以下是有关 Oracle 为什么采用这种(非标准)方式的更多信息:
为什么 Oracle 9i 将空字符串视为 NULL?< /a>
If you want to insert an empty string, you have to allow NULL values. Otherwise Oracle silently converts the empty string into NULL and you'll get the exception.
Another option would be to insert an empty string with a space
' '
but i think that would be a pain.Here are further informations on why Oracle does it this (non standard) way:
Why does Oracle 9i treat an empty string as NULL?
如果值为 null,则设置 param.Value = DBNull.Value,而不是将其设置为 null:
If the value is null, set param.Value = DBNull.Value, rather than setting it to null:
尝试
try