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

jGuru: Help: Retrieving and Displaying an Image from a Blob

 


[Exercise | API Docs | Short Course| Exercises]

Help is available for each task.

    Task 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.

             sQueryD = 
              "SELECT DISTINCT TColor " +
              "FROM TeeColor",
    
             sQueryP = 
              "SELECT TCBlob " +
              "FROM TeeColor " +
              "WHERE TColor = ?",
    

    Task 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.

          rs = stmt.executeQuery( sQueryD );
          while( rs.next() )
          {
            jcb.addItem( rs.getString( 1 ) );
          }
    

    Task 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().

          pstmt = con.prepareStatement( sQueryP );
    

    Task 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.

          pstmt.setString( 1, 
            (String)(jcb.getSelectedItem()) );
          rs = pstmt.executeQuery();
          if( rs.next() )
          {
            blob = rs.getBlob( 1 );
    
            iLength = (int)(blob.length());
            ii = new ImageIcon(
               blob.getBytes( 1, iLength )
                              );
    
            jlImage.setIcon( ii );
    

    Task 5

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

        if( con != null)
        {
          try { con.close(); }
          catch( Exception e ) {}
        }
    

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