C# 向sql server中的int列插入空值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11018939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert a null value to an int column in sql server
提问by
I have a subroutine to insert a record to sql server table. The code:
我有一个子程序来向 sql server 表插入一条记录。编码:
public void Insert_Met(int Counts, char Gender)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("@Counts", Counts);
parameters.Add("@Gender", Gender);
// run a stored procedure ExecuteNonQuery
}
I other line code,
我其他行代码,
int counts = Convert.ToInt32(numberUpdowncontrol1.Text);
// from a control, maybe empty then it is null.
Insert_Met(counts,'M');
My question is sometimes Counts can be null, so how to change my code?
我的问题是有时 Counts 可以为 null,那么如何更改我的代码?
Thanks,
谢谢,
采纳答案by Reed Copsey
You could use int? countsinstead of int counts, and check the value within your method:
您可以使用int? counts代替int counts,并检查您的方法中的值:
public void InsertMet(int? counts, char gender)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("@Counts", counts.HasValue ? counts.Value : (object)DBNull.Value);
parameters.Add("@Gender", gender);
// run a stored procedure ExecuteNonQuery
}
it is a numericupdown control in windows form. I feel that it is hard to assign a text to an int variable. How to change it?
它是一个 windows 形式的 numericupdown 控件。我觉得很难将文本分配给 int 变量。如何改变它?
In order to set the count value appropriately for the above, you could do:
为了为上述设置适当的计数值,您可以执行以下操作:
int value = (int)numberUpdowncontrol1.Value;
int? counts = !string.IsNullOrEmpty(numberUpdowncontrol1.Text) ? value : (int?)null;
InsertMet(counts, 'M');
回答by Pankaj
Following statement will always produce not null value
以下语句将始终产生非空值
int counts = Convert.ToInt32(null); // Result is 0
回答by priyanka
int count = !(count == 0)? count ? (object)DBNull.Value
-If, count is not zero save the count value to database -If it is zero save
-如果,计数不为零,将计数值保存到数据库 -如果为零保存

