在SQL Server数据库中保存图像文件时出现问题...

问题描述:

你好会员,
我需要一些帮助,如何从前端将图像文件保存在数据库中...我的前端是VC#...以下是我的代码,但是图像文件未保存在数据库中...

hello members,
i need some help that,how to save a image file in a database from front end...my front end is VC#...the following is my code but image file is not saved in database...

Program.Connection2Server();
            string updt = "";

            FileStream fs = new FileStream(curFileName,FileMode.OpenOrCreate,FileAccess.Read);
            //MessageBox.Show(fs.Length.ToString());

            byte[] rawdata=new byte[fs.Length];
            fs.Read(rawdata,0,System.Convert.ToInt32(fs.Length));
            fs.Close();
            updt = "update Faculty_details set Photo='"+rawdata+"'";
            Program.con.Close();




请帮助我....




plz guyz help me out....

我建​​议不要将文件保存在DB中.而不是使用文件路径&将其存储在数据库中.

FileStream st =新的FileStream(@"C:\ filename.jpg",FileMode.Open);
byte []缓冲区=新的byte [st.Length];
st.Read(buffer,0,(int)st.Length);
st.Close();



SqlConnection conn =新的SqlConnection("...");
SqlCommand cmd =新的SqlCommand("UPDATE SomeTable SET image = @ image WHERE ID = 1",conn);
cmd.Parameters.AddWithValue("@ image",缓冲区);
conn.Open();
int i = cmd.ExecuteNonQuery();
conn.Close();
i suggest not to save a file in a DB.. instead of it use a file path & stored it in DB.

FileStream st = new FileStream(@"C:\filename.jpg", FileMode.Open);
byte[] buffer = new byte[st.Length];
st.Read(buffer, 0, (int)st.Length);
st.Close();



SqlConnection conn = new SqlConnection("...");
SqlCommand cmd = new SqlCommand("UPDATE SomeTable SET image=@image WHERE ID = 1", conn);
cmd.Parameters.AddWithValue("@image", buffer);
conn.Open();
int i = cmd.ExecuteNonQuery();
conn.Close();


是的,我解决了这个问题:


yes i solved the problem:


FileStream st = new FileStream(curFileName, FileMode.Open);
            byte[] buffer = new byte[st.Length];
            st.Read(buffer, 0, (int)st.Length);
            st.Close();



            Program.Connection2Server();
            SqlCommand cmd1 = new SqlCommand("UPDATE Faculty_details SET photo=@image WHERE Faculty_code ='"+textBox1.Text+"'", Program.con);
            SqlParameter param;

            param=cmd1.Parameters.Add(new SqlParameter("@image", buffer));
            
            int i=cmd1.ExecuteNonQuery();
            Program.con.Close();



及其工作....



and its working....


使用参数化查询.
如果您通过串联构建SQL命令(如您所做的那样),则存在两个问题:
1)您将整个数据库置于意外或蓄意的SQL注入攻击的威胁之下,这很可能非常非常容易地损坏或破坏它.
2)它不起作用,因为原始图像字节将由SQL Server作为命令数据处理,而整个命令被拒绝为垃圾.
Use a parametrized query.
If you build your SQL command by concatenation (as you are doing) then there are two problems:
1) You put your whole database at risk from an accidental or deliberate SQL injection attack that could damage or destroy it very, very easily.
2) It won''t work, as the raw image bytes will be processed by the SQL server as command data and the whole command rejected as rubbish.