Solved

Generic JDBC ResultSetMetaData CAST code needed

Posted on 1998-12-01
6
285 Views
Last Modified: 2012-05-04
I use Java as CGI. I want to pass in a database table name
from an html page
and have my Java code build a web page with the database table column names
as html table column headers and put the data in the
html columns. Pretty basic stuff. The trick is being
able to cast the resultSet columns to the proper
java data types. I could probably do this with a little
thinking and effort, but I'm sure this has been done
a thousand times before and why re-invent the wheel
if you don't have to. What I would like is to see
some code that already does this. I expect that somebody
here could probably cut-n-paste the answer for me in
about 10 seconds.
Thanks!

0
Comment
Question by:mmoore
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
6 Comments
 
LVL 16

Expert Comment

by:heyhey_
ID: 1228605
do you need this piece of code ??

       int type;
            try {
                type = metaData.getColumnType(column+1);
            }
            catch (java.sql.SQLException e) {
                return super.getColumnClass(column);
            }

            switch(type) {
            case Types.CHAR:
             case Types.VARCHAR:
             case Types.LONGVARCHAR:
                 return String.class;
            case Types.BIT:
                 return Boolean.class;

            case Types.TINYINT:
             case Types.SMALLINT:
             case Types.INTEGER:
                 return Integer.class;

            case Types.BIGINT:
                 return Long.class;

             case Types.FLOAT:
            case Types.DOUBLE:
                 return Double.class;

    case Types.DATE:
                 return java.sql.Date.class;
             default:
                 return Object.class;
            }
        }
0
 
LVL 3

Author Comment

by:mmoore
ID: 1228606
Actually, I have that piece. What I need is the the casting.
I have a JFC example that shows a JDBCAdapter class which
uses an implementation of TableModel. This works fine but what I really want is to build an HTML page, not use a GUI. The TableModel takes raw objects with some information about the
type of object and POOF! (insert miracle here) the data is
displayed in tabular format in the JFC GUI. This miracle
must involve some casting, and this is what is unclear to me.
Here is my code so far, just to give a better idea of what
I am trying to do.
---------------------
import java.io.*;
import java.util.*;
import java.sql.*;  
import oracle.html.*;
import oracle.owas.wrb.services.http.*;
import java.net.URL;
import ibm.sql.*;

class table {

   static {
      try {
         // register the driver with DriverManager
         Class.forName("ibm.sql.DB2Driver");
      } catch (ClassNotFoundException e) {
         e.printStackTrace();
      }
   }

   public static void main(String argv[]) throws SQLException, IOException{
      HTTP request        = HTTP.getRequest();
      String table_name   = request.getURLParameter("table_name");
      String temp         = new String();
      Object dataObject;
      java.sql.Date d;
      int sw = 0;
      HtmlHead hd = new HtmlHead("IPROV Table Detail Report");
      HtmlBody bd = new HtmlBody();
      HtmlPage hp = new HtmlPage(hd,bd);
      bd.setBackgroundColor(Color.white);
     
      bd.addItem("<H2>"+table_name+" Details:<BR></H2>");
      try {
         String url = "jdbc:db2:db";
         Connection con = DriverManager.getConnection(url,"mmoore","passwd");
         Statement stmt;
         ResultSet rs;
         ResultSetMetaData md;
         stmt = con.createStatement();
         rs = stmt.executeQuery(
         "SELECT  * "+
         "  from iprov."+table_name);


         md = rs.getMetaData();
         bd.addItem("<TABLE BORDER=1>\n<TR>");
         int numberOfColumns = md.getColumnCount();

         for (int i = 0; i < numberOfColumns; i++) {
             bd.addItem("<TD>"+ md.getColumnLabel(i+1)+"</TD>");
         }
         bd.addItem("</TR>\n");

         while (rs.next()) {
           bd.addItem("<TR>");
           for (int i=1; i<= numberOfColumns; i++) {
           dataObject = rs.getObject(i);

// THIS IS WHERE THE TYPING AND CASTING SHOULD go
           
              bd.addItem("<TD>Data will go Here</TD>");
           }

           bd.addItem("</TR>\n");

         }
         bd.addItem("<TABLE>");


//       ********************************************************************
         bd.addItem("<BR><BR>Use your [BACK] key to go back.");
         rs.close();
         stmt.close();
         hp.printHeader();
         hp.print();

      }
      catch (SQLException se) {
         bd.addItem("</TABLE>");
         while (se != null) {
             bd.addItem("SQLState: " + se.getSQLState());
             bd.addItem("<BR>Message: " + se.getMessage());
             bd.addItem("<BR>Vendor code: " + se.getErrorCode() + "<BR>");
             se = se.getNextException();
          }
          bd.addItem("<CENTER><H3><FONT color=red>SOMETHING FAILED!</FONT></H3>");
          hp.printHeader();
          hp.print();
         
          return;
         }
      catch( Exception e ) {
          bd.addItem("</TABLE>");
          hp.printHeader();
          hp.print();
          e.printStackTrace();
         
          return;
      }
   }
}

0
 
LVL 16

Expert Comment

by:heyhey_
ID: 1228607
maybe i don't understand you but you have the real object (data)

    dataObject = rs.getObject(i);

if you want to now what is its class you can use
   dataObject.getClass().getName();

if you want to print it as string you can use
   dataObject.toString()

>> ... to cast the resultSet columns to the proper  java data types ...

but they are already casted to the proper Java type ... - you just have a variable of type Object that points to an Object from the appropriate class ....

hope this helps
  heyhey
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 3

Author Comment

by:mmoore
ID: 1228608
No, clearly it is I who does not understand. Apparently
all I had to do was :

         while (rs.next()) {
           bd.addItem("<TR>");
           for (int i=1; i<= numberOfColumns; i++) {
             dataObject = rs.getObject(i);
             bd.addItem("<TD>"+dataObject+"</TD>\n");
           }
           bd.addItem("</TR>\n");  ... chop ...

(actually it looks like I could have said:
             bd.addItem("<TD>"+rs.getObject(i)+"</TD>\n");
and saved the needless instanciation of dataObject.)


Hmmm, so if it is so easy, I wonder what that code
that you gave me in your first reply was all about?

Please submit an ANSWER rather than a COMMENTS so
I can award you the points!

Thanks again.

0
 
LVL 16

Accepted Solution

by:
heyhey_ earned 100 total points
ID: 1228609
you can use:
             bd.addItem("<TD>"+dataObject+"</TD>\n");
which is the same as
             bd.addItem("<TD>"+dataObject.toString()+"</TD>\n");

and you can get the object's class with
dataObject.getClass() (and the class name with dataObject.getClass().getName() ) ....
>> I wonder what that code that you gave me in your first reply was all about?
but only if you have the dataObject :-) - that is at least one row in the result set (or at least you should extract the first row). if your resultSet is empty, or you can't extract the first row (because somebody else will handel the resultSet object) you need to extract the class information from the MetaData object (and that was the code i posted)

best regards
  heyhey
0
 
LVL 3

Author Comment

by:mmoore
ID: 1228610
tried to give you the points bug got
-
Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, webmaster@experts-exchange.com and inform them of the time the error occurred, and anything
you might have done that may have caused the error.

Premature end of script headers: /usr/local/xx/v1.3/secure-bin/AnswerQ

------------
reported the problem, will try again later.
Cheers
0

Featured Post

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to convert from xls to xlsx using java 7 159
CSV file parsing thru Java 13 54
printf performancy 11 104
hashmap order 17 63
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question