C#中DBNull问题
当数据库中一个字段不是必填项时,在往数据库中插入数据的时候往往会插入一个空字符串就草草了事了。在这里用DBNull可以解决这个问题
/// <summary> /// 插入数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, RoutedEventArgs e) { string name = txtName.Text; string age = txtAge.Text; string height = txtHeight.Text; object objName; if (name.Length <= 0) { objName = DBNull.Value; } else { objName = name; } object objAge; if (age.Length <= 0) { objAge = DBNull.Value; } else { objAge = age; } object objHeight; if (height.Length <= 0) { objHeight = DBNull.Value; } else { objHeight = height; } SqlHelper.ExecuteNonQuery(@"insert into T_Person(Name,Age,Height) values (@Name,@Age,@Height)", new SqlParameter("@Name", objName), new SqlParameter("@Age", objAge), new SqlParameter("@Height", objHeight)); } /// <summary> /// 读出数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button3_Click(object sender, RoutedEventArgs e) { DataSet ds = SqlHelper.ExecuteDataSet("select * from T_Person where id=2"); string name; if (ds.Tables[0].Rows[0]["Name"] == DBNull.Value) { name = null; } else { name = ds.Tables[0].Rows[0]["Name"].ToString(); } int? age; if (ds.Tables[0].Rows[0]["Age"] == DBNull.Value) { age = null; } else { age = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString()); } txtName.Text = name; txtAge.Text = age.ToString(); txtHeight.Text=ds.Tables[0].Rows[0]["Height"].ToString(); }