2013-03-07 72 views
4

我要感謝所有誰在上一個問題中提供幫助。 但現在,我遇到了另一個聲明,即saveimageto MS訪問問題。 首先,我想問一下,在ms access數據庫中,Datatype應該放置附件嗎?C#將圖片插入Ms Access

我的代碼:

private void button2_Click(object sender, EventArgs e) 
     { 

      OleDbCommand cmd = new OleDbCommand(); 
      cmd.CommandType = CommandType.Text; 
      cmd.CommandText = "insert into Table1 (id,picture) values ('" + textBox1.Text + "')"; 

      cmd.Connection = con; 
      con.Open(); 
      cmd.ExecuteNonQuery(); 
      System.Windows.Forms.MessageBox.Show("Created", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); 
      con.Close(); 

     } 

我插入我的圖片PictureBox的使用打開文件對話框。

+0

Hi Tham JunKai, 請問你能說明是什麼問題嗎? – Micha 2013-03-07 14:25:37

回答

10

首先,使用參數。切勿爲SQL命令串聯字符串,因爲它會將自身打開爲SQL注入。這是一種容易遵循的良好做法,可以避免您在未來遇到很多麻煩。

這就是說,這樣的事情應該工作:

// You've got the filename from the result of your OpenDialog operation 
var pic = File.ReadAllBytes(yourFileName); 
OleDbCommand cmd = new OleDbCommand(); 
cmd.CommandType = CommandType.Text; 
cmd.CommandText = "insert into Table1 (id, picture) values (@p1, @p2)"; 
cmd.Parameters.AddWithValue("@p1", TextBox1.Text); 
cmd.Parameters.AddWithValue("@p2", pic); 
cmd.ExecuteNonQuery(); 

從內存中引用在這裏,但讓我知道如果代碼給你添麻煩了。如果我沒有記錯的話,應該這樣做。

編輯 - 如果您在PictureBox控件上預加載圖像,請將該圖像轉換爲字節數組,然後使用該字節數組作爲第二個參數。

編輯(2).-稍加說明。如果你正在從一個文件中獲取你的圖像,你就有一條路徑;那麼你可以使用File.ReadAllBytes(string path)。在我的示例中,我假設yourFileName是成功運行OpenDialog後所選文件的文件和路徑名。因此可以使用這樣的:

byte[] fromPath = File.ReadAllBytes(@"C:\walls\aurora.jpg"); 

和你存儲到字節數組fromPath圖像,轉換成字節,並且準備在插入命令以用作上面看到。

,如果你從一個圖片框控件讓你的形象,事情有一點不同:

MemoryStream ms = new MemoryStream(); 
pictureBox1.Image.Save(ms, Imaging.ImageFormat.Jpeg); 
byte[] fromControl = ms.GetBuffer(); 

在我創建了一個MemoryStream這個例子中,用的內容填充它picturebox控件,然後將它傳遞給字節數組,我們再次準備將其用作插入查詢的參數。

哦,別忘了

using System.IO; 
using System.Drawing; 

添加到您的usings。

+0

Hello yourFileName的意思是?你有團隊觀察員,所以我可以問你更容易。? – 2013-03-07 14:54:50

+0

var pic = File.ReadAllBytes(pictureBox1);可以這樣使用? – 2013-03-07 14:57:45

+0

我要編輯我的答案,使其更加清晰。 – CMPerez 2013-03-07 16:15:35