2013-07-25 83 views
0

通過讀取圖片框中的圖像,我將圖像存儲到表test (id, name, image)中的數據庫中。在sql中插入和更新圖像

這是我的代碼:

private void browse_Click(object sender, EventArgs e) 
{ 
    OpenFileDialog openFileDialog1 = new OpenFileDialog(); 
    openFileDialog1.Filter = "(*.BMP;*.JPG;*.GIF;*.JPEG;*.PNG)|*.BMP;*.JPG;*.GIF;*.JPEG;*.PNG"; 
    if (openFileDialog1.ShowDialog() == DialogResult.OK) 
    { 
     imgloc = openFileDialog1.FileName.ToString(); 
     pictureBox1.ImageLocation = imgloc; 
    } 
} 

private void save_Click(object sender, EventArgs e) 
{ 
    byte[] img = null; 
    FileStream fs = new FileStream(imgloc, FileMode.Open, FileAccess.Read); 
    BinaryReader br = new BinaryReader(fs); 
    img = br.ReadBytes((int)fs.Length); 
    SqlConnection CN = new SqlConnection(constring); 
    string Query = "insert into test (id,name,image) values('" + txtid.Text + "','" + txtname.Text + "',@img)"; 
    CN.Open(); 
    cmd = new SqlCommand(Query, CN); 
    cmd.Parameters.Add(new SqlParameter("@img", img)); 
    cmd.ExecuteNonQuery(); 
    CN.Close(); 
} 

它的工作原理,但我想知道如何在這裏使用update命令。

+0

而不是'insert'使用'UPDATE'查詢 –

+0

你是什麼意思的「更新命令」? – Oscar

回答

0

您的代碼和查詢應該是這樣的:

SqlConnection CN = new SqlConnection(constring); 
string Query = "Update test Set [email protected],[email protected] where [email protected]" 
CN.Open(); 
cmd = new SqlCommand(Query, CN); 
cmd.Parameters.Add(new SqlParameter("@Image", img)); 
cmd.Parameters.Add(new SqlParameter("@Name",txtname.Text)); 
cmd.Parameters.Add(new SqlParameter("@id",txtid.Text)); 
cmd.ExecuteNonQuery(); 
CN.Close(); 
2
private void update_Click(object sender, EventArgs e) 
    { 
     byte[] img = null; 
     FileStream fs = new FileStream(imgloc, FileMode.Open, FileAccess.Read); 
     BinaryReader br = new BinaryReader(fs); 
     img = br.ReadBytes((int)fs.Length); 
     SqlConnection CN = new SqlConnection(constring); 

     // this is a smaple query for update statement and update where [email protected] 
     string Query = "update test set [email protected],[email protected] where [email protected] "; 

     CN.Open(); 
     cmd = new SqlCommand(Query, CN); 
     cmd.Parameters.Add(new SqlParameter("@img", img)); 
     cmd.Parameters.Add(new SqlParameter("@id", txtid.Text)); 
     cmd.Parameters.Add(new SqlParameter("@name", txtname.Text)); 
     cmd.ExecuteNonQuery(); 
     CN.Close(); 
    } 
0

使用您的ID字段只要刪除特定的記錄,並再次火保存查詢,如果更新是困難的。