使用带参数的SQL语句向数据库中插入空值
private void button1_Click(object sender, EventArgs e)
{
string name = textBox1.Text;
int age = Convert.ToInt32(textBox2.Text.Trim());
int? height = textBox3.Text.Trim().Length == 0 ? null : (int?)Convert.ToInt32(textBox3.Text.Trim());
bool? gender = textBox4.Text.Trim().Length == 0 ? null : (bool?)Convert.ToBoolean(textBox4.Text.Trim());
string sql = "insert into TblPerson values(@name,@age,@height,@gender)";
SqlParameter[] pms = new SqlParameter[] {
new SqlParameter("@name",SqlDbType.NVarChar,50){ Value=name},
new SqlParameter("@age",SqlDbType.Int){ Value=age},
//向数据库中插入null值,不能直接使用C#中的null,必须使用DBNull.Value
new SqlParameter("@height",SqlDbType.Int){ Value=height==null?DBNull.Value:(object)height},
new SqlParameter("@gender",SqlDbType.Bit){ Value=gender==null?DBNull.Value:(object)gender}
};
_02封装SqlHelper类.SqlHelper.ExecuteNonQuery(sql, pms);
MessageBox.Show("插入成功!");
}