我应该建立软件健身房。 我想在健身房为每位员工附上一张照片。 所以我按照youtube上的优秀指南解释了如何将图像附加到数据。 问题是,当我附上图片时,表格中的新行连接而不是现有的行
谢谢!!!!using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
namespace gym
{
public partial class Load_Save : Form
{
OleDbConnection DBConnection = new OleDbConnection();
OleDbDataAdapter DataAdapter;
DataTable LocalDataTable = new DataTable();
int rowPosition=0;
int rowNumber=0;
public Load_Save()
{
InitializeComponent();
}
private void Load_Save_Load(object sender, EventArgs e)
{
ConnectToDatabase();
}
private void ConnectToDatabase()
{
DBConnection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Directory.GetCurrentDirectory() + "\\data.mdb";
DBConnection.Open();
DataAdapter = new OleDbDataAdapter("Select * From Workers", DBConnection);
DataAdapter.Fill(LocalDataTable);
if(LocalDataTable.Rows.Count !=0)
{
rowPosition = LocalDataTable.Rows.Count;
}
}
private void btnBrowse_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
btnSave.Enabled = true;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
StoreData(ConvertImageToBytes(pictureBox1.Image));
}
private byte[] ConvertImageToBytes(Image InputImage)
{
Bitmap BmpImage = new Bitmap(InputImage);
MemoryStream Mystream = new MemoryStream();
BmpImage.Save(Mystream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] ImageAsBytes = Mystream.ToArray();
return ImageAsBytes;
}
private void StoreData(byte[] ImageAsBytes)
{
if(DBConnection.State.Equals(ConnectionState.Closed))
DBConnection.Open();
try
{
MessageBox.Show("Saving image at index: " + rowPosition.ToString());
OleDbCommand oledbInsert = new OleDbCommand("Insert INTO Workers (id,firtsname,lastname,email,username,job,passw,permission,phone,dateofjoin,photo) VALUES('" + "','" + "','" + "','" + "','" + "','" + "','" + "','" + "','" + "','" + "',@Myphoto)", DBConnection);
OleDbParameter imageParameter = oledbInsert.Parameters.AddWithValue("@photo", SqlDbType.Binary);
imageParameter.Value = ImageAsBytes;
imageParameter.Size = ImageAsBytes.Length;
int rowsAffected = oledbInsert.ExecuteNonQuery();
MessageBox.Show("data stored succ in" + rowsAffected.ToString() + " ROW");
rowPosition++;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
MessageBox.Show(ex.StackTrace.ToString());
}
finally
{
RefreshDBCconnection();
}
}
private void RefreshDBCconnection()
{
DBConnection.Close();
LocalDataTable.Clear();
ConnectToDatabase();
}
}
}
答案 0 :(得分:0)
如果要更新数据库中已存在的内容,那么在SQL查询中,您必须使用UPDATE statement(ID为旧记录)而不是INSERT。像这样:
UPDATE Workers SET photo=@photo WHERE id=@old_id
或者作为变体(如果你想同时更新多个记录/多个字段并简化插入/更新代码,那么很好用) - 你可以BEGIN TRANSACTION删除旧记录&#34 ;删除",使用具有相同ID的INSERT插入新的,然后COMMIT TRANSACTION。