C # storing images in binary format to MSSQL (1)

Source: Internet
Author: User
Tags sql server books

I just learned how to store images in the MSSQL database today and decided to leave notes so as not to forget.

SQL Server Books Online provides usage conditions for three binary data types:

1. When the size of all input data in the table column is fixed (and the length is smaller than 8000 bytes), the standard binaryBinaryData type;

2. UseVarbinaryData type;

3. UseVarbinary (max)Data type.

This exploitationVarbinary (max)Data Type storage image:

I will test the following in the MSSQL database:

Insert[Blog]. [DBO]. [img] (data)

SelectBulkcolumn

From OpenRowSet(Bulk'G: \ vs test \ websites \ mail \ images \ 1.gif ',Single_blob)AsBlob

// The result is displayed successfully.

OpenRowSetSQL statements allow SQL to be provided from external data sourcesProgramTo access data. Bulk is particularlyOpenRowSetData source provider designed to insert files and images.

Then, the image is displayed on the ASPX page:

Front-end page:

<Form ID = "form1" runat = "server">
<Div>
<Asp: Image id = "image1" runat = "server" imageurl = "~ /Images/12.gif"/>
<Asp: button id = "button1" runat = "server" text = "button" onclick = "button#click"/>

</Div>
</Form>

Aspx. CSCodeAs follows:

Protected void button#click (Object sender, eventargs E)
{
String STR = "Server = (local); User = grid; database = blog; Password = grid ";
Sqlconnection conn = new sqlconnection (STR );
// String cmd = "insert into IMG (IMG) values ()";
Conn. open ();
String cmd = "Select data from IMG ";
Sqlcommand COM = new sqlcommand (CMD, Conn );
Com. commandtype = commandtype. text;
Sqldatareader DR = com. executereader ();
Dr. Read ();
Response. binarywrite (byte []) Dr ["data"]);
Conn. Close ();
}

click the button to display the saved image.

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.