开发者

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开发者_如何学C 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;
}


try

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜