Sun Java Solaris Communities My SDN Account Join SDN
 
Tutorials & Code Camps

jGuru: Storing an Image in a Blob

 


[Help | API Docs | Short Course| Exercises]

Exercise Note: This program requires a DBMS that supports Blob columns. The version of Cloudscape used in the course does not. The exercise has been tested against UDB2/NT and DB2/400. Slight changes in the DDL to create the table may be required for other databases. The remainder of the program should run properly with a JDBC 2.0 Compliant driver.

4J management wants a program that will display the various Tee shirt design images. "Just toss 'em in the database and let us see them. Easy enough, right?" was the way it was put to Duane and Chrissie. The developers had been avoiding Blobs, but decide that now is the time to use them. The table TeeColor will contain a character column with the color/design name and a Blob column containing the image. The first requirement is to create and populate the table.

Prerequisites

Skeleton Code

Tasks

  1. The program has been set up with corresponding arrays which contain the color name and the image data. The images themselves are provided in the Solution directory for this exercise. Your first task is to set up the driver and user information for a database that supports Blob columns.

  2. Add code for the DDL statement to create the TeeColor table. The SQL for DB2 is:

    CREATE TABLE TeeColor (
      TColor      VARCHAR (10)  NOT NULL,
      TCBlob      BLOB    (64K) NOT NULL,
      PRIMARY KEY( TColor )
                          )
    

    This will create a Blob column capable of holding up to 64k of binary data.

  3. Add code to prepare pstmt with the DML

    INSERT INTO TeeColor VALUES( ?, ? )
    

    to insert rows into the table.

  4. Add code to load the data and insert the rows: To avoid side issues, the program assumes that the image files reside in the same directory and accesses them as a File. You should set up a loop in which the image name is obtained from the asImages array, then create a File and FileInputstream for each image. Set the prepared statement's first parameter to the color name from asColors and the second parameter as a BinaryStream using the created FileInputstream and File.length(). Total the inserted rows in iRowCount.

Where help exists, the task numbers above are linked to the step-by-step help page.

Solution Source

Demonstration

When this program has been compiled and run against the database, the TeeColor table will be created and populated with a character column and a Blob column containing images as shown below:

Beige       *Black4j*

Black       *Black4j*

Blue        *Black4j*

Green       *Black4j*

White       *Black4j*

Yellow      *Black4j*

Exercises

Short Course

Copyright 1996-2000 jGuru.com. All Rights Reserved.