简体   繁体   English

ASP.Net C#CreateParameter,带有空字符串

[英]ASP.Net C# CreateParameter with empty string

In my ASP.net C# web project I have a query command object that has parameters. 在我的ASP.net C#web项目中,我有一个包含参数的查询命令对象。 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. 我使用Oracle数据库,我使用System.Data.OracleClient作为提供程序。

If you want to insert an empty string, you have to allow NULL values. 如果要插入空字符串,则必须允许NULL值。 Otherwise Oracle silently converts the empty string into NULL and you'll get the exception. 否则,Oracle会将空字符串静默转换为NULL,您将获得异常。

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? 以下是Oracle为什么采用这种(非标准)方式的进一步信息: 为什么Oracle 9i将空字符串视为NULL?

If the value is null, set param.Value = DBNull.Value, rather than setting it to null: 如果值为null,请设置param.Value = DBNull.Value,而不是将其设置为null:

if (value == null)
{
    param.Value = DBNull.Value;
}
else
{
    param.Value = value;
}

尝试

param.Value = string.IsNullOrEmpty(value) ? DBNull.Value : value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM