Store an Image(OLE Object) into Access Data Base
C# Winform application Store an Image into Access Data Base
用以下方法
/// 2010-02-26 Forever
private void SaveImageInDataBase()
{
OleDbConnection conn = null;
try
{
string strDBFile = Environment.CurrentDirectory + @"/Test.mdb";
string connstr = "Jet OLEDB:Database Password=;Data Source='" + strDBFile + "';Password=;Provider='Microsoft.Jet.OLEDB.4.0'";
conn = new OleDbConnection(connstr);
OleDbCommand cmd;
String strimg = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "//test2.bmp";
//Read Image Bytes into a byte array
//Initialize byte array with a null value initially.
byte[] imageData = null;
//Use FileInfo object to get file size.
FileInfo fInfo = new FileInfo(strimg);
long numBytes = fInfo.Length;
//Open FileStream to read file
FileStream fStream = new FileStream(strimg, FileMode.Open, FileAccess.Read);
//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);
//When you use BinaryReader, you need to supply number of bytes to read from file.
//In this case we want to read entire file. So supplying total number of bytes.
imageData = br.ReadBytes((int)numBytes);
//Set insert query
string qry = "insert into [admin] ([Logo]) values(@Logo)";
//Initialize SqlCommand object for insert.
cmd = new OleDbCommand(qry, conn);
OleDbParameter p1 = new OleDbParameter("@Logo", OleDbType.Binary);
p1.Value = imageData;
cmd.Parameters.Add(p1);
//We are passing Original Image Path and Image byte data as sql parameters.
//SqlCom.Parameters.Add(new SqlParameter("@ImageData", (object)imageData));
//Open connection and execute insert query.
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
finally
{
conn.Close();
}
}