Java.sql.Statement: setQueryTimeout(int seconds) ???

Anyboby knows if this method is working with MySQL-Connector JDBC driver ?
If not, is there another way to time out a select query ?
Thanks a lot
Ludovic

Do you have an idea of how I can test it ?Well you can time a select query and afterwards set the timeout interval to a value less than the time of the query. Start the same query and check the results.
So long.

Similar Messages

  • Java.sql.Statement.setFetchSize(int) option for non-scrollable result sets

    Hello!
    Our tests indicate that fetch size option mentioned makes visible difference in performance for non-scrollable result sets also. In the same time, it seems there is no way to set this option for such result sets at TopLink level, and default fetch size is always used instead.
    Can somebody propose a solution for this, I mean a way to specify custom fetch size (for results without any scrolling)?
    Thanks,
    Sergey

    To set the JDBC fetch size for a query, use the following APIs:
    int desiredFetchSize = 500;
    ReadAllQuery query = new ReadAllQuery(YourClass.class);
    CallQueryMechanism queryMechanism =
    (CallQueryMechanism) query.getQueryMechanism();
    DatabaseCall call = queryMechanism.getCall();
    call.setResultSetFetchSize(desiredFetchSize);
    If you wish to set the fetch size for all queries, consider using named queries for all queries (see the TopLink documentation for more information on named queries), and then configure them on startup.
    Information taking from Metalink Note:237093.1

  • Method Not Suypported- Statement.setQueryTimeout(int)

    I'm having a bout of confusion over error messages. We're using a product to monitor our IT resources and currently trying to monitor Informix DB response through JDBC.
    Our software package said we should use the Informix JDBC 1.40 but only 1.50 was available to us. From the language I think the help file was written when 1.4 was out because it makes no mention of earlier or later versions.
    The notes for 1.5 say JDK 1.1.6, 1.1.7, or 1.1.8 needs to be installed. (no mention of a JRE, though I assume JDK convers that as well.) We installed JDK 1.1.8
    Our monitor is erroring out, quickly, saying that
    connect error,
    Method not supported : Statement.setQueryTimeout(int).
    I'm having trouble identifing where this is unsupported. Would someone recognize, does this means ....
    Infromix JDBC 1.5 is making a request that JDK 1.1.8 doesn't support?
    Informix JDBC 1.5 is making a request that the java interface on the Informix DB server doesn't recognize?
    JDK 1.1.8 is lacking some requirement?
    Some other inbetween layer (which I am not recognizing) is the problem?
    A later version of JRE is running and causing the conflict (perhaps this method is obsolete in JRE 1.3.0)
    I confirmed that the JDK 1.1.8 is in the first in the path and gets executed by default. (instead of another version on the NT server). There is another version 1.3.0 installed.

    I have no expertise with informix, but I know that the Statement.setTimeOut(int) method is supported in 1.1.x, therefore this is most likely being generated by the driver or the database.

  • Problem in addBatch method in java.sql.Statement Interface

    Hi
    I am facing a problem java.lang.UnsupportedOperationException when using addbatch() method of java.sql.Statement Interface.
    Please suggest solutions.
    Thanks
    nsgindia

    Your JDBC driver doesn't support batch operation, try another driver(not all databases support batch'es eg MySQL)

  • Java.beans.Statement & java.sql.Statement

    My old code from jdk1.3.1 throws the ambiguous class thingie-mo-bob. Why did they implement the new java.beans.Statement, and is there anyway to make it default to the old java.sql.Statement without having to go through all the old code and add import java.sql.Statement. I have like 200 jsp files 'n it will take a loooong time!
    Pete

    There r two ways to do this.
    (i) One is Implement the java.sql.Statement
    like
    package java.beans;
    public interface Statement implements
    java.sql.Statement {
    }What? Are you suggesting he edit the source code for java.beans.Statement and make it implement java.sql.Statement?? I would most certainly not suggest that solution- beside violating the licensing agreement, it has troubling consequences since you are basically redefining the structure of a class in a way that makes no functional sense- that is, there is no reason for java.beans.Statement to implement methods like getConnection() and the other signatures of java.sql.Statement.
    I'm not sure if I'm reading your response correctly or not, but I would definitely not refactor java.beans.Statement just to get this problem solved with out editing files ... ... since java.sql.Statement is used so widely, perhaps they should have considered a different name for java.beans.Statement , although you hate to base a name off of what's going to cause the least problems, rather then what makes the most sense ... ... any way, I guess it doesn't matter now: the name has been selected .... I'd be interested to hear how you solved the problem.

  • MS Access queries different to Java SQL statements

    Ok, i dont understand something:
    My program is connected to a MSAccess datasource. The query in MSAccess is
    SELECT *
    FROM Food_Data
    WHERE Description Like 'Cheese*';
    ...but this wont work with a Java SQl query. I have to use this instead:
    String query = "SELECT * FROM Food_Data " +
              "WHERE Description LIKE 'Cheese%'";
    Surely java would just passes the string query to MSAccess. But no. Java needs '%' as the wildcard, and MSAccess needs '*' as the wildcard.
    Can anyone please explain this to me?

    Well % is the standard wildcard character for SQL as defined by the ANSI standard. MS Access just doesn't conform to this standard.
    Having said that, I'm still kind of astonished that it doesn't work :-)
    The JDBC driver should pass the statement "as is" to the underlying DBMS, but obviously the JDBC/ODBC bridge does some "quirking". But maybe it
    s the ODBC datasource. I can see a "ExtendedAnsiSQL" setting in one of my Access ODBC settings, maybe that changes something.

  • Java.sql.Statement hangs

    I'm having trouble executing the following statement. It never moves past execute(String sql)
    execute("insert into wtchangerequest2master(IDA2A2,WTCHGREQUESTNUMBER,MARKFORDELETEA2) select IDA2A2,WTCHGREQUESTNUMBER,MARKFORDELETEA2 from ccrmaster where ccrmaster.ida2a2=239207");
    whereas the following line executes perfectly
    execute("select distinct ida2a2 from ccrmaster");
    The statement that fails with Statement.execute works in sqlplus.
    Anybody have any ideas?

    Println("1 pre select");
    Execute("select ...");
    Println("2 post select");
    Println("3 pre insert select");
    Execute("insert ... Select ...");
    Println("4 post insert select");
    The app prints 1, 2, and 3, but hangs on the second execute and never gets to 4. No exception, no stack trace. It doesn't terminate. It just sits there.
    The pseudo might be a little rough.. I sent this from my phone.

  • About java.sql.Statement

    Hi friends, i want to ask if there is any way to display the complete statement as a string after setting it's parameters(that is for debuging purpose).

    Hi friends, i want to ask if there is any way to
    display the complete statement as a string after
    setting it's parameters(that is for debuging purpose).JDBC related questions should be asked in the JDBC forum.
    Your subject line is contraindicative to your question which is about PreparedStatements.
    The answer to your question is no. You can however use a tracing driver that will log your queries so that you can see what is going on. Look at http://www.p6spy.com/

  • Does Java support mutliple sql statements in one call?

    statment.executeUpdate("DROP DATABASE IF EXISTS diy55;CREATE DATABASE IF NOT EXISTS diy55 DEFAULT CHARACTER SET utf8;GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,ALTER,INDEX,USAGE on diy55.* TO 'diy55'@'localhost' identified by 'diy55';FLUSH PRIVILEGES;");Java seemes doesn't support multiple sql statements in one call, just like PHP mysql_query(), is it?

    Then just extend the java.sql.Statement to your own Statement class and write logic which splits the given query at the right places and executes them one by one.
    That the mysql_query() already has it built-in wouldn't say that it isn't possible in Java. Comparing with PHP is a bit pointless, it is a completely different language.

  • Java.sql.SQLException: Io exception: End of TNS data channel

    Hello folks,
    Has amyone encountered this exception? If so, could you please shed some light for what might be going wrong?
    Here is my confuguration:
    400MB RAM
    1.2GHTz processor
    Win2K Pro
    Oracle server 9.0.1
    JDBC Thin driver (libs for 9.0.1)
    Scenario:
    My Java code uses Oracle Spatial to insert SDO_GEOMETRY objects into my DB model.
    I have a config file where I store my connection properties, e.g.,
    <DBConnection name="twatest">
    <JDBCDriver>oracle.jdbc.driver.OracleDriver</JDBCDriver>
    <URL>jdbc:oracle:thin:@saturn:1521:saturn</URL>
    <Username>user1</Username>
    <Password>twatest</Password>
    </DBConnection>
    We have 2 schemas defined: user1 and twatest.
    The problem first occured when I switched from user1 to twatest. Consequent attempt to run the process as user user1 failed! The Java SQL statements do not use schemas (so they default, I suppose, to the default schema for that particular user, in our case being user1-->user1, twatest-->twatest).
    The problem happens in the following Java class (search for "HERE" to see where exactly the problem occurs):
    package com.vividsolutions.twatest;
    import java.util.*;
    import java.sql.*;
    import oracle.sql.*;
    import oracle.sdoapi.OraSpatialManager;
    import oracle.sdoapi.geom.*;
    import oracle.sdoapi.adapter.*;
    import oracle.sdoapi.sref.*;
    import com.vividsolutions.twatest.parser.*;
    import com.vividsolutions.twatest.config.*;
    import com.vividsolutions.twatest.model.*;
    * This class is responsible for loading lakes into the SDO Oracle Spatial DB.
    public class LakeLoader
    static boolean initialized = false;
    private static GeometryFactory gF;
    private static SRManager srManager;
    private static SpatialReference sref;
    private static GeometryAdapter sdoAdapter;
    public static void loadLake(EdgedLake slake, Connection conn) throws Exception {
    com.vividsolutions.jts.geom.Envelope e = slake.getEnvelope();
    if (e == null) {
    System.out.println("Invalid envilope (feature ID="+slake.getFeatureId()+")! Ignoring...");
    return; // ignore lake - it's invalid (no envilope)
    if (!initialized) {
    initialize(conn);
    initialized = true;
    Geometry geom;
    STRUCT str;
    // insert Lake
    String lakeQuery = "INSERT INTO lake " +
    "(lake_id, area, bounding_box, name, instantiation_date) " +
    "VALUES(?,?,?,?,?)";
    PreparedStatement ps = conn.prepareStatement(lakeQuery);
    int lakeId = getId(Lake.ID, conn);
    ps.setInt(1, lakeId);
    ps.setDouble(2, Double.parseDouble(slake.getArea()));
    // Creates a 2-D rectangle (special case of Polygon geometry).
    geom = gF.createRectangle(e.getMinX(), e.getMinY(), e.getMaxX(), e.getMaxY());
    ps.setObject(3, sdoAdapter.exportGeometry(STRUCT.class, geom));
    ps.setString(4, slake.getName());
    ps.setTimestamp(5, new Timestamp(new java.util.Date().getTime()));
    ps.executeUpdate(); // <-- HERE I got: java.sql.SQLException: Io exception: End of TNS data channel
    //ps.close();
    String ringQuery = null;
    int ringId = 0;
    List shellEdges = slake.getShellEdges();
    if (shellEdges != null && shellEdges.size() > 0) { // if there is valid shell, insert it...
    // insert shell Rings
    ringQuery = "INSERT INTO ring (ring_id, lake_id, type) VALUES(?,?,?)";
    ps = conn.prepareStatement(ringQuery);
    ringId = getId(Ring.ID, conn);
    ps.setInt(1, ringId);
    ps.setInt(2, lakeId);
    ps.setString(3, Ring.SHELL);
    ps.executeUpdate();
    //ps.close();
    // insert shell ring Edges
    insertEdges(shellEdges, lakeId, Ring.SHELL, ringId, conn);
    List holeEdges = slake.getHoleEdges();
    if (holeEdges != null && holeEdges.size() > 0) { // if there are valid holes, insert them...
    // insert hole Rings
    ringQuery = "INSERT INTO ring (ring_id, lake_id, type) VALUES(?,?,?)";
    ps = conn.prepareStatement(ringQuery);
    ringId = getId(Ring.ID, conn);
    ps.setInt(1, ringId);
    ps.setInt(2, lakeId);
    ps.setString(3, Ring.HOLE);
    ps.executeUpdate();
    //ps.close();
    // insert hole ring Edges
    insertEdges(holeEdges, lakeId, Ring.HOLE, ringId, conn);
    ps.close();
    private static void insertEdges(List edges, int lakeId, String ringType,
    int ringId, Connection conn) throws Exception {
    if (!initialized) {
    initialize(conn);
    initialized = true;
    Geometry geom;
    STRUCT str;
    // insert shell ring Edges
    String edgeQuery = "INSERT INTO edge " +
    "(edge_id, lake_id, ring_type, ring_id, edge_sequence, shape) " +
    "VALUES(?,?,?,?,?,?)";
    int edge_sequence = 0;
    for (Iterator it=edges.iterator(); it.hasNext(); ) {
    Edge edge = (Edge)it.next();
    geom = gF.createLineString(LakeFactory.edgeToArray2D(edge)); // 2-dimensional coordinates
    PreparedStatement ps = conn.prepareStatement(edgeQuery);
    int edgeId = getId(Edge.ID, conn);
    ps.setInt(1, edgeId);
    ps.setInt(2, lakeId);
    ps.setString(3, ringType);
    ps.setInt(4, ringId);
    ps.setInt(5, edge_sequence++);
    ps.setObject(6, sdoAdapter.exportGeometry(STRUCT.class, geom));
    ps.executeUpdate();
    ps.close();
    * @param key This can be: "lake", "ring", or "edge".
    * @param conn The connection to use.
    * @return the unique ID corresponding to the given key.
    public static int getId(String key, Connection conn) {
    int id = -1;
    try {
    String query = "SELECT "+key+"_SEQUENCE.NEXTVAL FROM DUAL";
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(query);
    while (rs.next()) {
    id = rs.getInt(1);
    stmt.close();
    } catch(SQLException sqle) {
    sqle.printStackTrace();
    return id;
    private static void initialize(Connection conn) throws Exception {
    gF = OraSpatialManager.getGeometryFactory();
    // Set spatial reference system in which the geometries will be created
    srManager = OraSpatialManager.getSpatialReferenceManager(conn);
    sref = srManager.retrieve(8307);
    gF.setSpatialReference(sref);
    sdoAdapter = OraSpatialManager.getGeometryAdapter("SDO", "8.1.6",
    null, STRUCT.class, null, conn);
    public static void main(String args[]) throws Exception
    String[] xmlLakeFiles = {
    "lakes101to1400.xml",
    "lakes1401to10000.xml",
    "lakes10001to20000.xml",
    "lakes20001to30000.xml",
    "lakes30001to40000.xml",
    "lakes40001to50000.xml",
    "lakes50001to60000.xml"
    PropertyManager pm = new PropertyManager();
    int numberOfLoadedLakes = 0;
    try {
    pm.initialize();
    Map modelMap = (Map)pm.get(XMLConfigFile.MODEL_MAP);
    LakeModel lakeModel = (LakeModel)modelMap.get(LREConcreteLakeModel.NAME);
    Connection connection = ConnectionManager.getConnection();
    lakeModel.setConnection(connection);
    for (int i=0; i<xmlLakeFiles.length; i++) {
    long then = System.currentTimeMillis();
    System.out.println("Loading lake "+xmlLakeFiles[i]+"...");
    numberOfLoadedLakes = lakeModel.loadModel(xmlLakeFiles);
    long now = System.currentTimeMillis();
    System.out.println("Loaded "+numberOfLoadedLakes+" lakes!");
    System.out.println("Execution time: "+(now-then)/1000+" seconds!");
    System.out.println("Loading lake "+xmlLakeFiles[i]+"...done!");
    connection.close();
    } catch(Exception e) {
    e.printStackTrace();
    My client class calls LakeLoader.loadLake() method in a loop to load a bunch of Lake objects into the DB. The first lake in the list is created without problems, but when the 2-nd lake is being inserted, I get an exception at the preparedStatement.executeUpdate() statement. This happens consistently.
    I tried to find information on this on the net, but seems that this problem only happened when people dealt with LOBs?!
    Thank you very much!
    Georgi

    Suresh -- I'd probably log a TAR with Oracle support for this question if you definitely need it resolved. Support have access to all manner of existing cases, so this may be something they have seen before.
    cheers
    -steve-

  • How to use count sql statement?

    i've never used the count function and i'm not sure how to use it to print it onto a html page...my code is below...
    <%
    String tot = (String)session.getAttribute("total");
    int total = Integer.parseInt(tot);
    Class.forName("org.postgresql.Driver");
    // create connection url
    String URL2 = "jdbc:postgresql://dbhost/ug59sxn";
    // pass database parameters to JDBC driver
    Connection Conn2 = DriverManager.getConnection(URL2, "ug59sxn", "hupeswop");
    // query statement
    Statement SQLStatement2 = Conn2.createStatement();
    // generate query
    String Query2 = "SELECT COUNT(*) FROM userteam WHERE total > '"+total+"'";
    // get result code
    ResultSet SQLResult2 = SQLStatement2.executeQuery(Query2);
    int position = (int)SQLResult2 + 1;
    %>
    <TD valign=top>
    <P align=center><FONT size=+1>Welcome <%= session.getAttribute("fName") %> <%= session.getAttribute("surname") %><BR>
    Your Team, <%= session.getAttribute("teamname") %>, are currently lying in position <FONT color=red><% out.println(position) %></font>, with <FONT color=red><%= session.getAttribute("total") %></font> points.<BR>
    </FONT></P>
    <P align=justify>      Use the shorcuts on the left to visit different sections of the game.
    You can change your squad around to prepare for forthcoming games (fixtures can be found in the statistics section),
    transfer a player in to your squad to add some depth or replace injured members, or perhaps browse the statistics section to see how your team is doing in the FFL table.</P>
    <HR>
    <%
    SQLResult2.close();
    SQLStatement2.close();
    Conn2.close();
    %>
    i get the following errors:
    type Exception report
    message Internal Server Error
    description The server encountered an internal error (Internal Server Error) that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: Unable to compile class for JSPNote: sun.tools.javac.Main has been deprecated.
    An error occured between lines: 62 and 84 in the jsp file: /main2.jsp
    Generated servlet error:
    /home/students/ug/ug59sxn/servlets-local/work/localhost/myapp/main2$jsp.java:80: Invalid cast from java.sql.ResultSet to int.
    int position = (int)SQLResult2 + 1;
    ^
    An error occurred at line: 88 in the jsp file: /main2.jsp
    Generated servlet error:
    /home/students/ug/ug59sxn/servlets-local/work/localhost/myapp/main2$jsp.java:108: Invalid type expression.
    out.println(position)
    ^
    An error occurred at line: 88 in the jsp file: /main2.jsp
    Generated servlet error:
    /home/students/ug/ug59sxn/servlets-local/work/localhost/myapp/main2$jsp.java:111: Invalid declaration.
    out.write("</font>, with <FONT color=red>");
    ^
    3 errors, 1 warning
    if anyone can help me out, please do so..thanx in advance...

    You cannot cast a ResultSet object (or any other object for that matter) to a primitive (such as an int)
    Replace the following line of code:
    int position = (int)SQLResult2 + 1;with this:
    int position = 0;
    if(SQLResult2.next())
      position = SQLResult2.getInt(1) + 1;
    }Additionally I noticed that you have put single quotes around total in the following line:
    String Query2 = "SELECT COUNT(*) FROM userteam WHERE total > '"+total+"'";Are you sure that the total column in the userteam table is of string type? If not, you don't need the single quotes.

  • Java.sql.PreparedStament

    when i use the java.sql.statement i cant create it with scrollable property. like this:
    // Create a Statement object that will be used to excecute the query.
    // The arguments specify that the returned ResultSet will be
    // scrollable, read-only, and insensitive to changes in the db.
    Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    // Run the query, creating a ResultSet
    ResultSet r = statement.executeQuery(query);
    the java.sql.PreparedStatement is scrollable or can be ???
    regards

    Connection class has this method (signature copied and pasted from my 1.3 javadoc):
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException

  • Numeric Overflow; nested exception is java.sql.SQLException: Numeric Overfl

    Dear Team,
    We are getting below errors in java,
    SQL state [99999]; error code [17026]; Numeric Overflow; nested exception is java.sql.SQLException: Numeric Overflow
    java.sql.SQLException: Numeric Overflow
    at oracle.jdbc.driver.NumberCommonAccessor.throwOverflow(NumberCommonAccessor.java:4380)
    at oracle.jdbc.driver.NumberCommonAccessor.getInt(NumberCommonAccessor.java:214)
    at oracle.jdbc.driver.OracleResultSetImpl.getInt(OracleResultSetImpl.java:896)
    at oracle.jdbc.driver.OracleResultSet.getInt(OracleResultSet.java:434)
    Thanks,
    selva
    Edited by: SELVAPA on Apr 25, 2013 4:05 PM

    >
    at oracle.jdbc.driver.OracleResultSet.getInt(OracleResultSet.java:434)
    >
    That 'getInt' method returns a Java 'int'. It will attempt to convert the actual data value in the result set column to an int.
    If the value is too large, too small or isn't even numeric you will get an exception.
    Isolate the problem (e.g. by debugging) to the row giving the exception and then examine the actual data value. If you are using NetBeans (or other) you can use the 'getString' method to see what the value is that is causing the problem.
    The actual 'solution' to the problem depends on your database, the table column definition and the business rules being implemented.
    You table could contain 'dirty' data and contain values larger than you want to be stored.
    Or your actual data could be correct and you are just using 'getInt' instead of 'getBigDecimal' or other method to get the value.
    Don't apply a 'solution' until you actually know what the problem is and the proper solution to implement.

  • Populating JTable table from sql statement.

    Trying to teach myself a combanation of things. Since Oracle is my background java to oracle is only a natural. Now this code I'm trying to select some rows and then display those rows in a table. Simple concept as a teaching aid to me. I won't go into what I went through to get this far, just say there have been quite a few fall starts. Now this code works; however it returns ten rows (one for each tablespace) and displays row 1 ten times. Not quite what I had in mind.
    I have got a simple select statment in my code:
    select tablespace_name,initial_extent,next_extent,pct_increase, status
    from dba_tablespaces order by tablespace_name
    package TableTest;
    // java imports
    import java.util.Vector;
    import java.awt.event.*;
    import java.awt.Toolkit;
    import java.awt.*;
    import javax.swing.*;
    // sql imports
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.sql.PreparedStatement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    public class TableTest extends JFrame
      Connection conn;  // database connection object
      Statement stmt;   // statement object
      ResultSet rslt;   // result set object
      //private vars
      private String userName         = "bubbalouie";
      private String password         = "helpmeimsinking";
      private String sid              = "rob";
      private String port             = "1521";
      private String server           = "w2sd001";
      private String connectString    = "jdbc:oracle:thin:@"+server+":"+port+":"+sid;
      private int numCols             = 5;
      private String sqlStmt          = null;
      private String status           = null;
      public TableTest()
        // Get content pane
        Container contentPane = getContentPane();
        // set layout manager
        contentPane.setLayout(new BorderLayout());
        // create some places to put dat
        Vector data    = new Vector();
        Vector columns = new Vector();
        Vector colHeads = new Vector();
        colHeads.addElement("tablespace name");  // this is ugly fix later
        colHeads.addElement("initial extent");
        colHeads.addElement("next extent");
        colHeads.addElement("pct increase");
        colHeads.addElement("status");
        // construct a simple sql statement
        sqlStmt = "select  tablespace_name, initial_extent, next_extent, pct_increase, status";
        sqlStmt = sqlStmt+" from dba_tablespaces order by tablespace_name";
        try
          // connect to database
          DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
          Connection conn = DriverManager.getConnection(connectString, userName, password);
          // select data into object
          stmt = conn.createStatement();
          rslt = stmt.executeQuery(sqlStmt);
          while (rslt.next())
            for ( int i=0; i<numCols; i++ )
              columns.addElement(rslt.getObject(i+1));  // get the i+1 object
            }  // end for
            data.addElement(columns);
          }    // end while
          // create the table
          JTable table = new JTable(data,colHeads);
          // add table to scroll pane
          int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
          int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
          JScrollPane jsp = new JScrollPane(table,v,h);
          // Add scroll pane to content pane
          contentPane.add(jsp, BorderLayout.CENTER);
        } catch (SQLException ex)
          String msg = "SQL error: "+ex.toString();
        } catch (Exception ex)
          String msg = "Error: "+ex.toString();
      }                                     // end constructor
      public static void main(String[] args) {
          TableTest frame = new TableTest();
          frame.setSize(500, 400);
          frame.setTitle("TableTest");
          frame.setVisible(true);
    }  // TableTest end class

    if you are interested here is a generic table model for displaying ResultSets in a JTable. The resultset needs to support calling resultset meta data and the basic methods in there but then it should support anything you give it.
    import java.sql.*;
    import java.util.*;
    import javax.swing.table.*;
    public class ResultSetTableModel extends AbstractTableModel{
      Vector rows;          
      int[] types;          
      String[] names;     
      public ResultSetTableModel(ResultSet rs)throws SQLException{
        ResultSetMetaData rsmd = rs.getMetaData();          
        types = new int[rsmd.getColumnCount()];          
        names = new String[rsmd.getColumnCount()];          
        for(int n=0;i<types.length;n++){               
          types[n] = rsmd.getColumnType(n+1);
          names[n] = rsmd.getColumnName(n+1);     
        rows = new Vector();
        while(rs.next()){
          Vector aRow = new Vector();
          for(int j=0;j<types.length;j++){
               switch(types[j]){
              case Types.TINYINT:
                aRow.addElement(new Byte(rs.getByte(j+1)));
                break;
              case Types.SMALLINT:
                aRow.addElement(new Short(rs.getShort(j+1)));
                break;
                 case Types.INTEGER:
                   aRow.addElement(new Integer(rs.getInt(j+1)));
                   break;
                 case Types.BIGINT:
                   aRow.addElement(new Long(rs.getLong(j+1)));
                   break;
                 case Types.REAL:
                   aRow.addElement(new Float(rs.getFloat(j+1)));
                   break;
                 case Types.FLOAT:
                   aRow.addElement(new Double(rs.getDouble(j+1)));
                   break;
                 case Types.DOUBLE:
                   aRow.addElement(new Double(rs.getDouble(j+1)));
                   break; 
                 case Types.DECIMAL:
                   aRow.addElement(rs.getBigDecimal(j+1));
                   break;
                 case Types.NUMERIC:
                   aRow.addElement(new Long(rs.getLong(j+1)));
                   break;
                 case Types.BIT:
                   aRow.addElement(new Boolean(rs.getBoolean(j+1)));
                   break;
                 case Types.BINARY:
                   aRow.addElement(rs.getBytes(j+1));
                   break;
                 case Types.DATE:
                   aRow.addElement(rs.getDate(j+1));
                   break;
                 case Types.TIME:
                   aRow.addElement(rs.getTime(j+1));
                   break;
                 case Types.TIMESTAMP:
                   aRow.addElement(rs.getTimestamp(j+1));
                   break;           
                 default:
                   aRow.addElement(rs.getString(j+1));
          rows.addElement(aRow);           
      public Class getColumnClass(int column){
        switch(types[column]){
          case Types.BIT:
            return Boolean.class;
          case Types.DATE:
            return java.sql.Date.class;
          case Types.TIME:
            return java.sql.Time.class;
          case Types.TIMESTAMP:
            return java.sql.Timestamp.class;
          default:
            return Object.class;     
      public int getRowCount(){
        return rows.size();     
      public int getColumnCount(){
        return types.length;     
      public Object getValueAt(int row, int column){
        Vector aRow = (Vector) rows.elementAt(row);
        return aRow.elementAt(column);
      public String getColumnName(int column){
        return names[column];
    }

  • Java.sql.Date vs java.util.Date vs. java.util.Calendar

    All I want to do is create a java.sql.Date subclass which has the Date(String) constructor, some checks for values and a few other additional methods and that avoids deprecation warnings/errors.
    I am trying to write a wrapper for the java.sql.Date class that would allow a user to create a Date object using the methods:
    Date date1 = new Date(2003, 10, 7);ORDate date2 = new Date("2003-10-07");I am creating classes that mimic MySQL (and eventually other databases) column types in order to allow for data checking since MySQL does not force checks or throw errors as, say, Oracle can be set up to do. All the types EXCEPT the Date, Datetime, Timestamp and Time types for MySQL map nicely to and from java.sql.* objects through wrappers of one sort or another.
    Unfortunately, java.sql.Date, java.sql.Timestamp, java.sql.Time are not so friendly and very confusing.
    One of my problems is that new java.sql.Date(int,int,int); and new java.util.Date(int,int,int); are both deprecated, so if I use them, I get deprecation warnings (errors) on compile.
    Example:
    public class Date extends java.sql.Date implements RangedColumn {
      public static final String RANGE = "FROM '1000-01-01' to '8099-12-31'";
      public static final String TYPE = "DATE";
       * Minimum date allowed by <strong>MySQL</strong>. NOTE: This is a MySQL
       * limitation. Java allows dates from '0000-01-01' while MySQL only supports
       * dates from '1000-01-01'.
      public static final Date MIN_DATE = new Date(1000 + 1900,1,1);
       * Maximum date allowed by <strong>Java</strong>. NOTE: This is a Java limitation, not a MySQL
       * limitation. MySQL allows dates up to '9999-12-31' while Java only supports
       * dates to '8099-12-31'.
      public static final Date MAX_DATE = new Date(8099 + 1900,12,31);
      protected int _precision = 0;
      private java.sql.Date _date = null;
      public Date(int year, int month, int date) {
        // Deprecated, so I get deprecation warnings from the next line:
        super(year,month,date);
        if(! isWithinRange(this))
          throw new ValueOutOfRangeException((RangedColumn)this, "" + this);
      public Date(String s) {
        super(0l);
        // Start Cut-and-paste from java.sql.Date.valueOf(String s)
        int year;
        int month;
        int day;
        int firstDash;
        int secondDash;
        if (s == null) throw new java.lang.IllegalArgumentException();
        firstDash = s.indexOf('-');
        secondDash = s.indexOf('-', firstDash+1);
        if ((firstDash > 0) & (secondDash > 0) & (secondDash < s.length()-1)) {
          year = Integer.parseInt(s.substring(0, firstDash)) - 1900;
          month = Integer.parseInt(s.substring(firstDash+1, secondDash)) - 1;
          day = Integer.parseInt(s.substring(secondDash+1));
        } else {
          throw new java.lang.IllegalArgumentException();
        // End Cut-and-paste from java.sql.Date.valueOf(String s)
        // Next three lines are deprecated, causing warnings.
        this.setYear(year);
        this.setMonth(month);
        this.setDate(day);
        if(! isWithinRange(this))
          throw new ValueOutOfRangeException((RangedColumn)this, "" + this);
      public static boolean isWithinRange(Date date) {
        if(date.before(MIN_DATE))
          return false;
        if(date.after(MAX_DATE))
          return false;
        return true;
      public String getRange() { return RANGE; }
      public int getPrecision() { return _precision; }
      public String getType() { return TYPE; }
    }This works well, but it's deprecated. I don't see how I can use a java.util.Calendar object in stead without either essentially re-writing java.sql.Date almost entirely or losing the ability to be able to use java.sql.PreparedStatement.get[set]Date(int pos, java.sql.Date date);
    So at this point, I am at a loss.
    The deprecation documentation for constructor new Date(int,int,int)says "instead use the constructor Date(long date)", which I can't do unless I do a bunch of expensive String -> [Calendar/Date] -> Milliseconds conversions, and then I can't use "super()", so I'm back to re-writing the class again.
    I can't use setters like java.sql.Date.setYear(int) or java.util.setMonth(int) because they are deprecated too: "replaced by Calendar.set(Calendar.DAY_OF_MONTH, int date)". Well GREAT, I can't go from a Date object to a Calendar object, so how am I supposed to use the "Calendar.set(...)" method!?!? From where I'm sitting, this whole Date deprecation thing seems like a step backward not forward, especially in the java.sql.* realm.
    To prove my point, the non-deprecated method java.sql.Date.valueOf(String) USES the DEPRECATED constructor java.util.Date(int,int,int).
    So, how do I create a java.sql.Date subclass which has the Date(String) constructor that avoids deprecation warnings/errors?
    That's all I really want.
    HELP!

    I appreciate your help, but what I was hoping to accomplish was to have two constructors for my java.sql.Date subclass, one that took (int,int,int) and one that took ("yyyy-MM-dd"). From what I gather from your answers, you don't think it's possible. I would have to have a static instantiator method like:public static java.sql.Date createDate (int year, int month, int date) { ... } OR public static java.sql.Date createDate (String dateString) { ... }Is that correct?
    If it is, I have to go back to the drawing board since it breaks my constructor paradigm for all of my 20 or so other MySQL column objects and, well, that's not acceptable, so I might just keep my deprecations for now.
    -G

Maybe you are looking for