2013-07-25 67 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字段只要删除特定的记录,并再次火保存查询,如果更新是困难的。