ASP. NET accessing SQL Server database images

Source: Internet
Author: User

ASP. NET accessing SQL Server database images

Author: wyhw posting time: Recommendation degree:★View author information and authors collections


SQL Server provides a special data type: image, which is a type that contains binary data. The following example shows how to put text or photos in the database. In this article, we will see how to store and read images in SQL Server.

1. Create a table:
Create a table with the following structure in SQL Server:
Column name type objective
Id integer primary key ID
Imgtitle varchar (50) image title
Imgtype varchar (50) image type. ASP. NET to be identified type
Imgdata image is used to store binary data.

2. store images in the SQL Server database

To store tables, you must first upload them to your web server. You can develop a web form, it is used to import images from textbox Web Control in the client to your web server. Set your enctype attribute to myltipart/formdata.

Stream imgdatastream = file1.postedfile. inputstream;
Int imgdatalen = file1.postedfile. contentlength;
String imgtype = file1.postedfile. contenttype;
String imgtitle = textbox1.text;
Byte [] imgdata = new byte [imgdatalen];
Int n = imgdatastream. Read (imgdata, 0, imgdatalen );
String connstr = (namevaluecollection) Context. getconfig ("etettings") ["connstr"];

Sqlconnection connection = new sqlconnection (connstr );

Sqlcommand command = new sqlcommand
("Insert into imagestore (imgtitle, imgtype, imgdata)
Values (@ imgtitle, @ imgtype, @ imgdata) ", connection );

Sqlparameter paramtitle = new sqlparameter
("@ Imgtitle", sqldbtype. varchar, 50 );

Paramtitle. value = imgtitle;
Command. Parameters. Add (paramtitle );

Sqlparameter paramdata = new sqlparameter ("@ imgdata", sqldbtype. Image );
Paramdata. value = imgdata;
Command. Parameters. Add (paramdata );

Sqlparameter paramtype = new sqlparameter ("@ imgtype", sqldbtype. varchar, 50 );
Paramtype. value = imgtype;
Command. Parameters. Add (paramtype );

Connection. open ();
Int numrowsaffected = command. executenonquery ();
Connection. Close ();

3. Restore read from the database

Now let's read the data we put from SQL server! We will output the image to your browser, and you can store it to your desired location.

Private void page_load (Object sender, system. eventargs E)
{
String imgid = request. querystring ["imgid"];
String connstr = (namevaluecollection)
Context. getconfig ("etettings") ["connstr"];
String SQL = "select imgdata, imgtype from imagestore where id =" + imgid;
Sqlconnection connection = new sqlconnection (connstr );
Sqlcommand command = new sqlcommand (SQL, connection );
Connection. open ();
Sqldatareader DR = command. executereader ();
If (dr. Read ())
{
Response. contenttype = Dr ["imgtype"]. tostring ();
Response. binarywrite (byte []) Dr ["imgdata"]);
}
Connection. Close ();
}

Note that response. binarywrite is not response. Write.

The following is a program for saving and reading C # winform. Please compare the differences! (For convenience, I simplified the database fields to two: imgtitle and imgdata.

Using system;
Using system. drawing;
Using system. collections;
Using system. componentmodel;
Using system. Windows. forms;
Using system. Data;
Using system. IO;
Using system. Data. sqlclient;

Namespace windowsapplication21
{
/// <Summary>
/// Summary of form1.
/// </Summary>
Public class form1: system. Windows. Forms. Form
{
Private system. Windows. Forms. Button button1;
/// <Summary>
/// Required designer variables.
/// </Summary>
Private system. componentmodel. Container components = NULL;
Private string connectionstring = "Integrated Security = sspi; initial catalog =; Data Source = localhost ;";
Private sqlconnection conn = NULL;
Private sqlcommand cmd = NULL;
Private system. Windows. Forms. Button button2;
Private system. Windows. Forms. picturebox pic1;
Private system. Windows. Forms. openfiledialog openfiledialog1;
Private string SQL = NULL;
Private system. Windows. Forms. Label label2;
Private string nowid = NULL;

Public form1 ()
{
//
// Required for Windows Form Designer support
//
Initializecomponent ();
Conn = new sqlconnection (connectionstring );

//
// Todo: add Any constructor code after initializecomponent calls
//
}

/// <Summary>
/// Clear all resources in use.
/// </Summary>
Protected override void dispose (bool disposing)
{
If (conn. State = connectionstate. open)
Conn. Close ();
If (disposing)
{
If (components! = NULL)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );

}

# Region windows Form Designer generated code
/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
/// </Summary>
Private void initializecomponent ()
{
This. button1 = new system. Windows. Forms. Button ();
This. pic1 = new system. Windows. Forms. picturebox ();
This. button2 = new system. Windows. Forms. Button ();
This. openfiledialog1 = new system. Windows. Forms. openfiledialog ();
This. label2 = new system. Windows. Forms. Label ();
This. suspendlayout ();
//
// Button1
//
This. button1.location = new system. Drawing. Point (0, 40 );
This. button1.name = "button1 ";
This. button1.size = new system. Drawing. Size (264, 48 );
This. button1.tabindex = 0;
This. button1.text = "Add new image ";
This. button1.click + = new system. eventhandler (this. button#click );
//
// Pic1
//
This. pic1.location = new system. Drawing. Point (280, 8 );
This. pic1.name = "pic1 ";
This. pic1.size = new system. Drawing. Size (344,264 );
This. pic1.tabindex = 3;
This. pic1.tabstop = false;
//
// Button2
//
This. button2.location = new system. Drawing. Point (0,104 );
This. button2.name = "button2 ";
This. button2.size = new system. Drawing. Size (264, 40 );
This. button2.tabindex = 4;
This. button2.text = "Recovering images from the Database ";
This. button2.click + = new system. eventhandler (this. button2_click );
//
// Openfiledialog1
//
This. openfiledialog1.filter = "/" image file (*. jpg, *. BMP, *. GIF) | *. jpg | *. BMP | *. gif /"";
//
// Label2
//
This. label2.location = new system. Drawing. Point (0,152 );
This. label2.name = "label2 ";
This. label2.size = new system. Drawing. Size (264, 48 );
This. label2.tabindex = 5;
//
// Form1
//
This. autoscalebasesize = new system. Drawing. Size (6, 14 );
This. clientsize = new system. Drawing. Size (632,273 );
This. Controls. addrange (new system. Windows. Forms. Control [] {
This. label2,
This. button2,
This. pic1,
This. button1 });
This. Name = "form1 ";
This. Text = "form1 ";
This. Load + = new system. eventhandler (this. form#load );
This. resumelayout (false );

}
# Endregion
 
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[Stathread]
Static void main ()
{
Application. Run (New form1 ());
}

Private void button#click (Object sender, system. eventargs E)
{
Openfiledialog1.showdialog ();
  
If (openfiledialog1.filename. Trim ()! = "")
{
Fileinfo Fi = new fileinfo (openfiledialog1.filename );

String imgtitle = openfiledialog1.filename;
Int imgdatalen = (INT) Fi. length;
Byte [] imgdata = new byte [imgdatalen];
  
Stream imgdatastream = Fi. openread ();
Int n = imgdatastream. Read (imgdata, 0, imgdatalen );

If (conn. State = connectionstate. open)
Conn. Close ();
Connectionstring = "Integrated Security = sspi;" + "Initial catalog = mydb;" + "Data Source = localhost ;";
Conn. connectionstring = connectionstring;

Try
{
String myselectquery = "insert into imagestore (imgtitle, imgdata) values (@ imgtitle, @ imgdata )";
// String myselectquery = "Update imagestore set imgtitle = @ imgtitle, imgdata = @ imgdata ";
Sqlcommand mycommand = new sqlcommand (myselectquery, Conn );

Sqlparameter paramtitle = new sqlparameter ("@ imgtitle", sqldbtype. varchar, 50 );
Paramtitle. value = imgtitle;
Mycommand. Parameters. Add (paramtitle );

Sqlparameter paramdata = new sqlparameter ("@ imgdata", sqldbtype. Image );
Paramdata. value = imgdata;
Mycommand. Parameters. Add (paramdata );

Conn. open ();
Int numrowsaffected = mycommand. executenonquery ();
Conn. Close ();
}
Catch (exception ERR)
{
MessageBox. Show ("your input name may already exist in the database or it is empty. Please check it! "+ Err. tostring ());
}
Finally
{}
}

}

Private void form1_load (Object sender, system. eventargs E)
{
}

Private void button2_click (Object sender, system. eventargs E)
{
// Open the database connection
If (conn. State = connectionstate. open)
Conn. Close ();
Connectionstring = "Integrated Security = sspi;" + "Initial catalog = mydb;" + "Data Source = localhost ;";
Conn. connectionstring = connectionstring;

// Create a data adapter
String SQL = "select * From imagestore ";
Sqlcommand command = new sqlcommand (SQL, Conn );
 
Try
{Conn. open ();}
Catch (exception newerr)
{
MessageBox. Show ("data connection cannot be enabled! ");
}
Finally
{}

Sqldatareader DR = command. executereader ();
If (dr. Read ())
{
Fileinfo Fi = new fileinfo ("Temp ");
Filestream mystream = Fi. Open (filemode. Create );
Byte [] mydata = (byte []) Dr ["imgdata"]);
// Label2.text = "what you see now:" + Dr ["imgtitle"]. tostring ();
Foreach (byte A in mydata)
{
Mystream. writebyte ();
}
Mystream. Close ();
Image myimage = image. fromfile ("Temp ");
Pic1.image = myimage;
Pic1.refresh ();
Dr. Close ();

}
Else
{
MessageBox. Show ("data is not read successfully! ");
}
Conn. Close ();
}
}
}

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.