使用插入查询将员工图像与其他信息一起上载到SQL数据库中

时间:2012-09-17 20:59:56

标签: c# image insert

我在使用c#将员工照片上传到数据库时遇到问题。我有一个员工输入屏幕表格。在那个表格上有关于员工的各种信息(姓名,地址,工资,加入日期,出生日期,图片,手机号等)。

我的插入查询在没有图像的情况下运行良好。这是我的代码示例。

 query = "insert into tbl_emp values('" + txtempid.Text + "','" + txtempname.Text + "','"+ cmbSex.Text +"','"
                + cmbDepartment.Text +"','" + cmbEmpDesig.Text + "','" + cmbemptyp.Text + "','" 
                + txtsalary.Text + "','"+ txtParmanentAdd.Text +"','"+ txtPresentAdd.Text +"','"
                + txtContactNo.Text +"','"+ txtEmailAdd.Text +"','"+ dateBirth.Text +"','" 
                + dateJoin.Text + "','"+ txtCardNo.Text +"')";
           con.executeCmd_Sql(query);

请建议我如何插入图像以及其他信息。在此先感谢:)

2 个答案:

答案 0 :(得分:1)

(假设您使用的是ASP.NET网络表单) 的.aspx:

 <asp:Image runat="server" ID="img" ImageUrl="~/Chrysanthemum.jpg" />

codebehind(.cs):

 string pic = img.ImageUrl;

将实际图片(如二进制数据)保存到数据库中并不是一种最佳实践。这就是为什么你通常只需要获取图片的路径(如"~/mypicture.jpg")并将其保存为数据库中的字符串。基本上,您所要做的就是在查询中传入字符串pic

不相关:但您的查询对SQL注入非常开放。我建议你阅读link

答案 1 :(得分:0)

插入图像很简单。您只需将图像转换为字节数组即可。看看这段代码片段示例:

private void updatedata()
{

    //use filestream object to read the image.

    //read to the full length of image to a byte array.

    //add this byte as an oracle parameter and insert it into database.

    try
    {

        //proceed only when the image has a valid path

        if (imagename != "")
        {

            FileStream fs;

            fs = new FileStream(@imagename, FileMode.Open, FileAccess.Read);

            //a byte array to read the image

            byte[] picbyte = new byte[fs.Length];

            fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length));

            fs.Close();

            //open the database using odp.net and insert the data

            string connstr = @"Data Source=.;Initial Catalog=TestImage;
            Persist Security Info=True;User ID=sa";

            SqlConnection conn = new SqlConnection(connstr);

            conn.Open();

            string query;

            query = "insert into test_table(id_image,pic) values(" + 
            textBox1.Text + "," + " @pic)";

            SqlParameter picparameter = new SqlParameter();

            picparameter.SqlDbType = SqlDbType.Image;

            picparameter.ParameterName = "pic";

            picparameter.Value = picbyte;

            SqlCommand cmd = new SqlCommand(query, conn);

            cmd.Parameters.Add(picparameter);

            cmd.ExecuteNonQuery();

            MessageBox.Show("Image Added");

            cmd.Dispose();

            conn.Close();

            conn.Dispose();

            Connection();

        }

    }

    catch (Exception ex)
    {

        MessageBox.Show(ex.Message);

    }

}

如果您需要更多信息,请查看this website,其中说明了您需要了解的所有信息。这段代码片段是我从该网站粘贴的。

相关问题