0

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);

これらの他の情報と一緒に画像を挿入する方法を教えてください。前もって感謝します :)

4

2 に答える 2

1

(ASP.NET Webフォームを使用していると仮定).aspx:

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

codebehind(.cs):

 string pic = img.ImageUrl;

実際の画像(バイナリデータなど)をデータベースに保存することは、実際にはベストプラクティスではありません。そのため、通常は画像へのパス(のように"~/mypicture.jpg")を取得し、それを文字列としてデータベースに保存します。したがって、基本的にはpic、クエリで文字列を渡すだけです。

無関係:しかし、クエリはSQLインジェクションに対して非常にオープンです。このリンクを読むことをお勧めします

于 2012-09-17T21:12:40.170 に答える
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);

    }

}

あなたがより多くの情報を必要とするならば、あなたが知る必要があるすべてを説明しているこのウェブサイトを見てください。そのサイトからここに貼り付けたこのコードフラグメント。

于 2012-09-17T21:12:00.463 に答える