DB数据类型为整数时如何在插入时设置NULL值 [英] how to set the NULL value while insertion when DB datatype is integer
本文介绍了DB数据类型为整数时如何在插入时设置NULL值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
cmd = new SqlCommand( 从ProductDetails中选择productid,其中productname =' + ddlproductid.SelectedItem.ToString()+ ',con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
proid = dr [ 0 跨度>]的ToString();
}
dr.Close();
cmd.Dispose();
我有一个coloumn来插入
SqlParameter ProductID = new SqlParameter( ProductID, int .Parse(proid.ToString()));
问题是:
如何将int.Parse(proid.ToString())值设置为NULL插入。 db数据类型是整数
如果我将值传递给这个参数proid.ToString()它的工作
在某些情况下我没有传递任何值它会抛出转换错误而不是必须设置为DB中的NULL
解决方案
尝试这种方式并且不解析,因为它会抛出异常。 ?会使变量可以为空。
int ? proid = null ;
SqlParameter ProductID = new SqlParameter( ProductID ,proid);
使用 Convert.ToInt32方法(字符串) [ ^ ]
在您的情况下,它会像
SqlParameter ProductID = new SqlParameter( ProductID,Convert.ToInt32(proid));
cmd = new SqlCommand("select productid from ProductDetails where productname='" + ddlproductid.SelectedItem.ToString() + "'", con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
proid = dr[0].ToString();
}
dr.Close();
cmd.Dispose();
I had a coloumn to insert
SqlParameter ProductID = new SqlParameter("ProductID", int.Parse(proid.ToString()));
The Question is:
how to set the int.Parse(proid.ToString()) value as a NULL while insertion. the db datatype is integer
if i pass the value to this parameter proid.ToString() its working
in some cases i dosen't pass any values it throws me the conversionerror instead of that must be set as a NULL in DB
解决方案
Try this way and dont parse as it will throw exception. ? will make a varible nullable.
int? proid=null; SqlParameter ProductID = new SqlParameter("ProductID",proid);
Use Convert.ToInt32 Method (String)[^]
In your case it would be like
SqlParameter ProductID = new SqlParameter("ProductID", Convert.ToInt32(proid));
这篇关于DB数据类型为整数时如何在插入时设置NULL值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文