How to insert null into database?
Hi I am trying to insert null in a database column depending on a gridview datakeys value (if being "" insert null into database) However, I am getting a spac开发者_运维百科e ' ' inside the database column.
string sbcId = gvTest.DataKeys[gr.RowIndex]["myColumn"].ToString();
insgnp.Parameters.Add(new OleDbParameter("EMPID", (sbcId==""?DBNull.Value.ToString():sbcId)));
You have to rewrite your code:
if(string.IsNullOrEmpty(sbcId))
Parameters.Add(new OleDbParameter("EMPID", DBNull.Value));
else
Parameters.Add(new OleDbParameter("EMPID", sbcId));
The problem with the ternary if statement that you have is that its returntype must always be the same, which is why you cannot use it (string and DbNull.Value are not compatible)
Use DBNull.Value
, not DBNull.Value.ToString
. (With other parameter collection types in .NET just using null
would also work, but I'm not 100% sure about OleDbParameter
).
As for the tertiary operator. Don't cast to string, but cast the string to object:
sbcId=="" ? DBNull.Value : (object)sbcId
You need to use DBNull.Value
not DBNull.Value.ToString()
DBNull.Value.ToString()
is ''
This program gives
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("'{0}'", DBNull.Value.ToString());
}
}
}
Try below by removing ToString() after DBNull.Value
string sbcId = gvTest.DataKeys[gr.RowIndex]["myColumn"].ToString();
insgnp.Parameters.Add(new OleDbParameter("EMPID", (sbcId==""?DBNull.Value:sbcId)));
SQLString.Null
should do the job just fine :)
I prefer to use an extension method to handle instead of multiple if statements. This allows you to account for null or empty string values. Also allows it to be reusable.
public static object GetDBNullOrValue<T>(this T val)
{
bool isDbNull = true;
Type t = typeof(T);
if (Nullable.GetUnderlyingType(t) != null)
isDbNull = EqualityComparer<T>.Default.Equals(default(T), val);
else if (t.IsValueType)
isDbNull = false;
else if (t == typeof(string) && val != null)
{
string temp = val as String;
isDbNull = (temp == String.Empty);
}
else
isDbNull = (val == null);
return isDbNull ? DBNull.Value : (object)val;
}
Then you could use
Parameters.Add(new OleDbParameter("EMPID", sbcId.GetDBNullOrValue()));
If you Insert a non string value in the access database you may write the insert query in this way
Insert into tableName (column1,column2) values (NULL,NULL);
But you want to insert null value in Short Text or Long Text field in access you may write the insert query in this way
Insert into tableName (column1, column2) values('','');
your string like that
string value = "";
now add following line
if (value == ""){
value = "NULL";
}
now insert in db and check you have null value their be logical
精彩评论