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

jGuru: Retrieving and Displaying an Image from a Blob

 


[Help | API Docs | Short Course| Exercises]

Exercise Note: This program requires a DBMS that supports Blob columns. The exercise has been tested against UDB2/NT and DB2/400. You will need to set the driver and connection information for your database in the ConnectJ.properties file.

Now that the images are loaded into the database, it's time to write a program to display them. Duane and Chrissie use the basic code from Selecting Data and Presenting Information to present a Swing interface. As before, the Swing work is done for you.

After user information is keyed and the "Connect" button is pressed, the program will connect to the database, retrieve all distinct colors and load them into a combo box. From that point, the user can select a color and press the "Show It!" button. The program will retrieve the corresponding image from the Blob column in the database and display it. The Connection will be maintained until the program ends.

Prerequisites

Skeleton Code

Tasks

  1. Two query strings are required: one to select all distinct colors in the table and the other for Blob selection in a prepared statement. Here are the SQL statements needed:

    for sQueryD

    SELECT DISTINCT TColor 
      FROM TeeColor
    

    for sQueryP

    
    SELECT TCBlob 
      FROM TeeColor 
      WHERE TColor = ?
    

    Your job is to set up Strings with the appropriate SQL statements.

  2. In doConnect(), after connecting and creating a Statement, execute the DISTINCT query, retrieve the rows and load the color names into a combo box.

  3. Now that the program is connected, after closing the Statement and doing some screen setup, it is time to execute prepareStatement. This is still in doConnect().

  4. In doRetrieve(), set the String and excute the PreparedStatement query; Get the Blob and its length; Materialize the Blob data using Blob.getBytes() and use the resulting aray of bytes to create an ImageIcon with ImageIcon( byte[] ). ( Note that in Blob.getBytes(), the binary data starts at 1. ) Use JLabel.setIcon() to load the image to the JLabel.

  5. In EndApp(), insert code to close the connection.

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, the resulting display should look like this:

TeeColorsJ

Exercises



Short Course



About This Short Course



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