Free Newsletters:
DatabaseJournal  
DBANews
Search Database Journal:
 
HOME News MS SQL Oracle DB2 Access MySQL PostgreSQL PHP SQL Etc Scripts Links Discussion
internet.com

» HOME
» NEWS
» FEATURES
» SERIES
MS SQL
Oracle
MS Access
MySQL
DB2
» RESOURCES
Products
Scripts
Links
» DISCUSSION
» TECH JOBS

Marketplace Partners
Be a Marketplace Partner




internet.commerce
Be a Commerce Partner
Phone Cards
Best Price
Web Hosting Directory
Promotional Golf
Corporate Awards
Baby Photo Contest
Promotional Gifts
Online Education
Condos For Sale
Web Design
Online Education
KVM over IP
Cell Phones
Boat Donations




Google Display Ads in Your Pocket

Ballmer Ready to Move on Yahoo?

Acer Strong in Q1 With Aggressive Growth

internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers


Linked Data Planet Conference & Expo

CA ERwin® Data Modeler Proven database design and modeling. Efficiently analyze, design and deploy effective database solutions. Whitepaper: Manage SQL Server Deployments
Try it free: CA ERwin® Data Modeler


Solaris 8 Migration Assistant
Rapidly move your Solaris 8 application environments to new systems running Solaris 10 with the Solaris 8 Migration Assistant. Reduce migration risk while taking advantage of increased performance, reliability and security of the latest SPARC hardware platforms and Solaris 10 OS. »

 
Sun Eco Innovation: Good for Business, Good for the Environment
A complete solution to help you optimize and refresh your datacenter while properly recycling equipment and eliminating eWaste, including money-saving promotions to lower hardware acquisition costs. »

 
Sun Eco Innovation: Power Calculators
Power consumption has increasingly become a priority in customer's minds when purchasing new systems or storage. Sun's Power Calculators provide data on power consumption of Sun products allowing IT managers to better plan the power requirements in the datacenter to achieve better energy and cost savings. »

 
Optimize the Web Tier: Consolidate to Get More Performance in Less Space and Lower Power Consumption
Expansion in the Web tier is generally accomplished by adding more servers whenever extra capacity is needed. As the pool of servers grows larger, however, the complexity of the environment can grow exponentially. »
Related Articles
Storing Images and BLOB files in SQL Server Part 2
Storing Images and BLOB files in SQL Server

Production Manager (hands on)
Aquent
US-MA-Cambridge

Justtechjobs.com Post A Job | Post A Resume
MS SQL
March 7, 2008
Storing Images and BLOB files in SQL Server Part 3
By Don Schlichting

Storing Images and BLOB files in SQL Server Part 3

Introduction

In the first two articles of this series, BLOBs were defined along with scenarios of when to store them inside SQL Server rather than on the file system. Several different types of VARBINARIES were introduced, including the VARBINARY(MAX) data type which will be the focus of this article. The first code example loaded an image into the database then retrieved it using an ASPX page with a Binary Write. In this article, a web-based application will be created for inserting images into SQL Server. In addition, the examples from the first two articles will be expanded and improved.

SQL Test Database

To begin, create a test database and table for storing images using the following TSQL script:

USE master;
GO
CREATE DATABASE BLOBTest3;
GO
 
USE BLOBTest3;
GO
 
CREATE TABLE BLOBFromWeb
(
BLOBData varbinary(max)
);
 
GO

The script created a single database, containing a single table, containing a single column. The test column “BLOBData” uses the MAX keyword allowing it to store binaries of any size.

Next create a stored procedure that will be used by a web page for uploading images:

CREATE PROCEDURE WebUp
(
@FileData varbinary(max)
)
AS
 
INSERT INTO BLOBFromWeb
 (BLOBData)
VALUES
 (@FileData);

The stored procedure will pass one variable, the image “@FileData”, into SQL Server.

The rest of the examples in this series will use stored procedures rather than SQL statements. There are many benefits to using stored procedures, such as increased security, preventing SQL Injection attacks, portability, and performance.

Inserting into SQL from the Web

This example uses Microsoft Visual Studio 2008 to create a web form, which will ask the end user to browse to a file, and then upload the file into SQL Server. The application will also work in Visual Studio 2005. To begin, create a new web site and an aspx page using code behind. Drag a FileUpload and a Button control onto the form as shown below.

Switch to the source view of the page and change the default <form> tag to the following:

<form id="form1" runat="server" enctype="multipart/form-data">

The “enctype” specifies the how the form data is encoded.

Change back to the design view and double click the button to create an On Click event. This will bring up the code behind page as shown below:

At the top of the page, add using statements for the SQL:

using System.Data.Sql;
using System.Data.SqlClient;

And also a statement for the file system:

using System.IO;

Add the following code into Button1_Click event:


string sConn = @"server=.; database=BLOBTest3; Integrated Security=True";
 
SqlConnection objConn = new SqlConnection(sConn);
objConn.Open();
 
SqlCommand objCmd = new SqlCommand("WebUp", objConn);
objCmd.CommandType = CommandType.StoredProcedure;
 
SqlParameter paramFileData = objCmd.Parameters.Add("@FileData", SqlDbType.VarBinary);
paramFileData.Direction = ParameterDirection.Input;
 
byte[] bImage = new byte[FileUpload1.PostedFile.ContentLength];
Stream objStream = FileUpload1.PostedFile.InputStream;
objStream.Read(bImage, 0, FileUpload1.PostedFile.ContentLength);
 
paramFileData.Value = bImage;
 
objCmd.ExecuteNonQuery();
objConn.Close();

The first line in the statement sets the connection to SQL Server. The phrase “Integrated Security” means Windows security will be used rather than a SQL Login ID. Next the connection to the database is opened. After the database is opened, the next two lines create a SQL Command object.

SqlCommand objCmd = new SqlCommand("WebUp", objConn);
objCmd.CommandType = CommandType.StoredProcedure;

WebUp is the name of the stored procedure created eariler. It’s tied to the open database connection, then the SQL Command is told WebUp is a stored procedure rather than a TSQL text statement.

The stored procedure requires a single parameter, the image, to be passed in. In the next line, a parameter is created. The name “paramFileData” can be anything, there is nothting special about it, but the Parameters.Add, “@FileData” must match the paramater name in the stored procedure.

SqlParameter paramFileData = objCmd.Parameters.Add("@FileData", SqlDbType.VarBinary);

Now, with the paramater created, the direction is specified:

paramFileData.Direction = ParameterDirection.Input;

Any data being passed into SQL is a command type of Input, data coming out would be ParameterDirection.Output.

Ideally, at this point, the FileUpload control could pass the image directly into the stored procedure parameter, but this doesn’t work. Instead, a byte array is created with the size of the image:

byte[] bImage = new byte[FileUpload1.PostedFile.ContentLength];

Next a Stream is created pointing to the image content:

Stream objStream = FileUpload1.PostedFile.InputStream;

Lastly the Stream transferes the image into the byte array:

objStream.Read(bImage, 0, FileUpload1.PostedFile.ContentLength);

Now the image data can be passed into the SQL parameter and executed.

paramFileData.Value = bImage;
 
objCmd.ExecuteNonQuery();

Here is a link for the complete web application, both the design page and the code behind.

Running the Application

View the web page inside a browser and click the browse button. A Windows file chooser will appear as shown below:

Once a file is selected and the final Button is clicked, the SQL Stored procedure will be executed. Viewing the results inside SQL Server will show there is data, but not what it looks like.

Because there isn’t a BLOB viewer as part of SQL Server, we’ll create a viewer similar to the one in the previous article, but stored procedure driven.

Viewer

Create a simple stored procure that will select the image data using the TSQL code below:

CREATE PROCEDURE BLOBViewer
AS
 
SELECT BLOBData 
FROM BLOBFromWeb

Next create a aspx page with code behind. On the code behind page add using statements for SQL Server:

using System.Data.Sql;
using System.Data.SqlClient;

In the Page_load section, use the following code to execute the stored procedure just created.

string sConn = @"server=.; database=BLOBTest3; Integrated Security=True";
SqlConnection objConn = new SqlConnection(sConn);
objConn.Open();
 
SqlCommand objCmd = new SqlCommand("BLOBViewer", objConn);
objCmd.CommandType = CommandType.StoredProcedure;
 
SqlDataReader dr = objCmd.ExecuteReader();
dr.Read();
 
Response.BinaryWrite((byte[])dr["BLOBData"]);
 
objConn.Close();

The web viewer code used is very similar to the previous article. The CommandType has been changed to Stored Procedure, and the SQLCommand now uses the name of the procedure rather than a sql string to execute.

Conclusion

SQL Server can be a handy container for image and BLOB data. Working with binary data is somewhat different from working with ASCII. The data saved inside SQL Server isn’t visible like character data. In addition, special handling of the data, such as with a byte array, is required before sending the data to SQL Server. Overall, however, the working with BLOBS and SQL Server is very worthwhile.

» See All Articles by Columnist Don Schlichting

Tools:
Add databasejournal.com to your favorites
Add databasejournal.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed

MS SQL Archives

Download: SQL Backup & DBA Best Practices eBook
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers. Sponsored by HP, Citrix, and Intel.
IT in 2018: Download Free eBook By The Author Of "Does IT Matter?" Simple Registration Is Required.
Whitepaper: Enterprise Information Integration--Deployment Best Practices for Low-Cost Implementation
Five Trends for Application Development. Download Your Complimentary Report. Exclusive. Act Now.


Latest Forum Threads
MS SQL Forum
Topic By Replies Updated
How To Transfer Access Data Records To SQL ?? ankurdjariwala 1 May 8th, 12:24 PM
problem with federated server linking majidkhan 1 April 29th, 10:00 AM
"SELECT rowguidcol" from tables on linked servers? brentbordelon 1 April 25th, 04:12 PM
"SELECT rowguidcol" vs. "SELECT <actual name>" rgarrison 9 April 16th, 03:46 PM







JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES