Update Binary files in SQL Server using OleDbCommand object

Source: Internet
Author: User

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
//----------------------------------------------------------

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.