To update a binary file in SQL Server using the OleDbCommand object

Source: Internet
Author: User
To update a binary file in SQL Server using the OleDbCommand object
Author Zhu Yi
Using the Oledbconnectionoledbcommand in Ado.net makes it easy to update binaries 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
Set up a table below:
CREATE TABLE tb_test (ID int identity (1,1), photo image, constraint pk_tb_test key (ID))
First, save the files on your hard disk to the database (C #)
//----------------------------------------------------------
//----------------------------------------------------------
The following example saves the C:1.txt file to the Tb_test table in the database
//----------------------------------------------------------
//----------------------------------------------------------
Using System;
Using System.IO;?
Using System.Data;
Using System.Data.OleDb;
Class Image_test
{
[STAThread]
static void Main (string[] args)
{
Try
{
Initializing 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 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 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 ();
Perform
if (cmd. ExecuteNonQuery () = = 1)
Console.WriteLine ("OK");
Else
Console.WriteLine ("Fail");?
cn. Close ();
}
catch (Exception ex)
{
Console.WriteLine (ex. message);
}
}
}?
Iii. 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.