将 null 值插入到 sql 服务器中的 int 列
本文关键字:int 服务器 sql null 插入 | 更新日期: 2023-09-27 18:37:08
>我有一个子例程将记录插入sql服务器表。代码:
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
}
我其他行代码,
int counts = Convert.ToInt32(numberUpdowncontrol1.Text);
// from a control, maybe empty then it is null.
Insert_Met(counts,'M');
我的问题是有时计数可以为空,那么如何更改我的代码?
谢谢
您可以使用
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
}
它是 Windows 窗体中的数字上下控件。我觉得很难将文本分配给 int 变量。如何改变它?
为了为上述内容适当地设置计数值,您可以执行以下操作:
int value = (int)numberUpdowncontrol1.Value;
int? counts = !string.IsNullOrEmpty(numberUpdowncontrol1.Text) ? value : (int?)null;
InsertMet(counts, 'M');
以下语句将始终产生不为空的值
int counts = Convert.ToInt32(null); // Result is 0
int count = !(count == 0)? count ? (object)DBNull.Value
-如果计数不为零,则将计数值保存到数据库-如果是零保存