.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal

Home >> Code Snippets >> ADO.NET >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Reading BLOB Data from the Database

Posted By:Shashi Ray       Posted Date: November 27, 2009    Points: 10    Category: ADO.NET    URL: http://www.dotnetspark.com  


Reading BLOB Data from the Database

When creating a SqlDataReader object through the ExecuteReader method to read rows that contain BLOB data, use the CommandBehavior.SequentialAccess enumerated value. Without this enumerated value, the reader pulls data from the server to the client one row at a time. If the row contains a BLOB column, this might represent a large amount of memory. By using the enumerated value, you have a finer degree of control because the BLOB data will be pulled only when referenced (for example, by means of the GetBytes method, which you can use to control the number of bytes read). This is illustrated in the following code fragment.

// Assume previously established command and connection
// The command SELECTs the IMAGE column from the table
using(SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
  // Get size of image data-pass null as the byte array parameter
  long bytesize = reader.GetBytes(0, 0, null, 0, 0);
  // Allocate byte array to hold image data
  byte[] imageData = new byte[bytesize];
  long bytesread = 0;
  int curpos = 0;
  while (bytesread < bytesize)
    // chunkSize is an arbitrary application defined value 
    bytesread += reader.GetBytes(0, curpos, imageData, curpos, chunkSize);
    curpos += chunkSize;
// byte array 'imageData' now contains BLOB from database

Note   Using CommandBehavior.SequentialAccess requires you to access column data in a strict sequential order. For example, if the BLOB data is in column 3, and you also require data from column 1 and column 2, you must read columns 1 and 2 prior to reading 3.




Shashi Ray


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend