IntroductionSome times we need to store binary data in database. SQL Server provides a special data type called image that can hold such binary data. The examples of binary data include images, documents etc. In this article we will see how we can store and retrieve Images in SQL Server Database
Creating TablesIn order to work with the examples of this article you will need a table in some database (You may chose to create it in existing database or create a enw database all together) Following table explains structure of the table.:
Column NameDatatypePurposeIDInteger identity column Primary keyIMGTITLEVarchar (50) Stores some user friendly title to identity the imageIMGTYPEVarchar (50) Stores image content type. This will be same as recognized content types of ASP.NETIMGDATAImageStores actual image or binary data.
Storing Images in SQL Server Database
In order to store images to the table you will first upload them to your web server from the client browser. You can develop a web form that accepts image title via a TextBox web control and image file via HTML File Server Control. Make sure you set ENCTYPE Attribute of the form to multipart / form-data.
Stream IMGDataStream = file1.postedfile.inputstream;
INT IMGDATALEN = file1.postedfile.contentLENGTH;
String ImgType = file1.postedfile.contenttype;
String emgtitle = textbox1.text;
Byte [] IMGData = New byte [IMGDATALEN];
INT n = imgdatathastream.read (IMGDATA, 0, IMGDATALEN);
String connStr =
(NameValueCollection) context.getconfig
("appsettings")) ["connStr"];
SqlConnection Connection = New SqlConnection (connStr);
Sqlcommand command = new SQLCOMMAND
("INSERT IMAGTORE (Imgtitle, ImgType, IMGDATA)
VALUES (@Imgtitle, @ imgtype, @ imgdata) "; 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 ();
Retrieving Images from Database
Now, Let us Read The images from The Database We store Output The Image Directly To The Browser. You Can Instead Save It As a File or Do Whatever You Want.
Private Void Page_Load (Object Sender, System.EventArgs E)
{
String IMGID = Request.QueryString ["IMGID"];
String connStr = ((NameValueCollection)
Context.getConfig ("appsettings")) ["connStr"];
String SQL = "SELECT IMGDATA, IMGTYPE AMEGTORE 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 ();
}
In the above code we have opened a connection with our database. We. Since the image data is. Reading out data from the database and then images via SELECT datareader binary data we used Response.BinaryWrite instead of normal Response.Write, and saved to a file
String connectionstring = @ "provider = microsoft.jet.OLEDb.4.0;" @ "password =" "" "" "" "" "" "" user id = admin; data source = " Application.Startuppath @" / db.mdb "; string SQL = "select * from file"; OleDbConnection conn = new OleDbConnection (ConnectionString); OleDbCommand cmd = conn.CreateCommand (); cmd.CommandText = SQL; conn.Open (); OleDbDataReader dr = cmd.ExecuteReader ();
IF (Dr.Read ()) {string strfile = string.empty; strfile = Dr.getstring (1); byte [] by = (byte []) Dr.GetValue (2);
FileStream Fs = file.open (Strfile, Filemode.create, FileAccess.write); fs.write (by, 0, by.length); fs.close (); messagebox.show ("Read success!");} Dr.close (); conn.close (); reads the picture from the database and saves the file, which is the same as this.
Save files to the database
String connectionstring = @ "provider = microsoft.jet.OLEDb.4.0;" @ "password =" "" "" "" "" "" "" user id = admin; data source = " Application.Startuppath @" / db.mdb "; string SQL = "select * from document"; OleDbConnection conn = new OleDbConnection (ConnectionString); OleDbDataAdapter da = new OleDbDataAdapter (SQL, conn); OleDbCommandBuilder cmd = new OleDbCommandBuilder (da); DataSet ds = new DataSet ();
Conn (); da.fill (DS, "File"); DataTable DT = DS.TABLES [0]; DATAROW DR; if (Dt.Rows.count> 0) DR = DT.ROWS [0]; ELSE DR = DT.NEWROW (); DR [1] = txtFile.Text; filestream fs = file.open (txtfile.text, filemode.open, fileaccess.read); byte [] by = new byte [fs.length]; fs.read (by, 0, (int) fs.length); DR [2] = by; if (dt.rows.count <= 0) Dt.Rows.Add (DR); da.Update (DS, " file");
CONN.CLOSE (); fs.close ();