日期:2014-05-17  浏览次数:20979 次

varbinary(MAX)如何插入空值
/*photo字段是varbinary(MAX)类型,如果用户未选择文件,应该插入空值,但不知如何写代码?尝试了,用null不行,用DBNull.Value(会导致不是空值)也不行。
数据库中的对应字段已设置,允许为空。 */           
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
            {
                String sql = "insert into emp(name,age,photo) values(@name,@age,@photo)";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@name", textBox1.Text);
                cmd.Parameters.AddWithValue("@age", Convert.ToInt32(textBox2.Text));
                byte[] b;
                if (textBox3.Text != "")//用户选择了图像文件
                {
                    b = File.ReadAllBytes(textBox3.Text);
                    cmd.Parameters.AddWithValue("@photo", b);
                }
                else
                {
                    //如果用户未选择文件,应该插入空值,但不知如何处理?                 }
               
 
                conn.Open();
                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
 
                    MessageBox.Show(ex.Message);
                }
 
            }

------解决方案--------------------
用""这个不行吗
------解决方案--------------------
System.Data.SqlTypes.SqlBinary.Null