简体   繁体   中英

ASP.Net C# CreateParameter with empty string

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.

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?

If the value is null, set param.Value = DBNull.Value, rather than setting it to null:

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

尝试

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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