C#向Sql数据库插入控制

 1  string name = textBox1.Text;  2             int age = Convert.ToInt32(textBox2.Text.Trim());  3             int? height = textBox3.Text.Trim().Length == 0 ? null : (int?)Convert.ToInt32(textBox3.Text.Trim());  4             bool? gender = textBox4.Text.Trim().Length == 0 ? null : (bool?)Convert.ToBoolean(textBox4.Text.Trim());  5 
 6             string sql = "insert into TblPerson values(@name,@age,@height,@gender)";  7             SqlParameter[] pms = new SqlParameter[] {  8             new SqlParameter("@name",SqlDbType.NVarChar,50){ Value=name},  9             new SqlParameter("@age",SqlDbType.Int){ Value=age}, 10 
11             //向数据库中插入null值,不能直接使用C#中的null,必须使用DBNull.Value
12             new SqlParameter("@height",SqlDbType.Int){ Value=height==null?DBNull.Value:(object)height}, 13             new SqlParameter("@gender",SqlDbType.Bit){ Value=gender==null?DBNull.Value:(object)gender} 14  }; 15  _02封装SqlHelper类.SqlHelper.ExecuteNonQuery(sql, pms); 16             MessageBox.Show("插入成功!");

 

你可能感兴趣的:(C#向Sql数据库插入控制)