Update Binary files in SQL Server using OleDbCommand object
Author Zhu 'er
You can use OleDbConnectionOleDbCommand In ADO. NET to conveniently Update Binary files in SQL Server. The following is a detailed code demonstration.
Demo environment:
Database machine name: s_test
Login Name: sa
Password 7890
Database Name db_test
Create a table as follows:
Create table tb_test (id int identity (1, 1), photo image, constraint pk_tb_test primary key (id ))
1. save files on the hard disk to the database (C #)
//----------------------------------------------------------
//----------------------------------------------------------
// The following example saves the c: 1.txt file to the tb_test table of the database.
//----------------------------------------------------------
//----------------------------------------------------------
Using System;
Using System. IO ;?
Using System. Data;
Using System. Data. OleDb;
Class image_test
{
[STAThread]
Static void Main (string [] args)
{
Try
{
// Initialize OleDbConnection and OleDbCommand
OleDbConnection cn = new OleDbConnection ("provider = sqloledb; server = s_test; user id = sa; password = 7890; initial catalog = db_test ");
OleDbCommand cmd = new OleDbCommand ("INSERT tb_test (photo) VALUES (?) ", Cn );
// Open the file
FileStream fs = new FileStream ("c: 1.txt", FileMode. Open, FileAccess. Read );
Byte [] B = new Byte [fs. Length];
Fs. Read (B, 0, B. Length );
Fs. Close ();
// Open the connection
OleDbParameter prm = new OleDbParameter ("@ photo", OleDbType. VarBinary, B. Length ,?
ParameterDirection. Input, false, 0, 0, null, DataRowVersion. Current, B );
Cmd. Parameters. Add (prm );
Cn. Open ();
// Execute
If (cmd. ExecuteNonQuery () = 1)
Console. WriteLine ("OK ");
Else
Console. WriteLine ("Fail ");?
Cn. Close ();
}
Catch (Exception ex)
{
Console. WriteLine (ex. Message );
}
}
}?
3. Update the files saved in the database
//----------------------------------------------------------