将图片保存到数据库而不绑定源

时间:2015-05-12 19:33:59

标签: c#

我尝试使用Sqlcommand将图片保存到数据库中。当我保存时,有一个异常抛出说“不允许从数据类型varchar到varbinary(max)的隐式转换。使用CONVERT函数来运行此查询。” 这是代码:

private void btn_save_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        SqlCommand cmd1= new SqlCommand();
        SqlCommand cmd2 = new SqlCommand();
        string squ1;

        squ1 = "INSERT INTO Customer (cus_name, cus_address, cus_Image)Values('" + textBox1.Text + "' , '" + textBox2.Text  + "', '"+pictureBox1 .Image +"');";

        con.ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\ProgramData\MyDB\TestingDB.mdf;Integrated Security=True;Connect Timeout=30";
        con.Open();

        cmd1.Connection = con;
        cmd1.CommandText = squ1;
        cmd1.ExecuteNonQuery();
        con.Close ();
    }
    // the browser button to get a picture
    private void btn_browseImage_Click(object sender, EventArgs e)
    {
        OpenFileDialog f = new OpenFileDialog();
        if (f.ShowDialog () == DialogResult .OK )
        {
            pictureBox1.ImageLocation  = f.FileName;
        }

2 个答案:

答案 0 :(得分:1)

您必须将图像数据作为varbinary参数传递给查询:

using (var con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\ProgramData\MyDB\TestingDB.mdf;Integrated Security=True;Connect Timeout=30"))
using (var cmd1 = new SqlCommand("INSERT INTO Customer (cus_name, cus_address, cus_Image)Values(@name, @address, @image);", con))
{
    var imageData = new MemoryStream();
    pictureBox1.Image.Save(imageData, pictureBox1.Image.RawFormat);

    cmd1.Parameters.AddWithValue("@name", textBox1.Text);
    cmd1.Parameters.AddWithValue("@address", textBox2.Text);
    cmd1.Parameters.Add("@image", SqlDbType.VarBinary).Value = imageData.ToArray();


    con.Open();
    var result = cmd1.ExecuteNonQuery();
}

您应该真正了解如何使用SqlCommand来避免将来的SQL注入。

答案 1 :(得分:0)

语句'"+pictureBox1.Image +"'实际上会调用pictureBox1.Image.ToString(),而不是图像的二进制内容。使用SqlParameters添加二进制数据。您可以找到解决方案here ...