Overhead of using java.sql.STRUCT

I am calling a stored proc passing in a java.sql.STRUCT
created via DDL statement
CREATE TYPE APPDBA.MY_STRUCT
AS OBJECT
USER_KEY INTEGER,
USER_HOME VARCHAR2(32)
My question is:
when i am creating a structdescriptor from java
oracle.sql.StructDescriptor sDesc =
oracle.sql.StructDescriptor.createDescriptor ("APPDBA.MY_STRUCT", mConnection)
what exactly goes on under the hood here? Does the driver
make a round trip call to the DB every time?
Does it do some sort of caching?
Thanks.

Thanks for your reply. But please take a look at the following code snippet. It intends to add a Timestamp representing the
start of a day (time component 00:00:00) to a time component (having Date to 01-01-1970):
        Time time = new Time(61952000);
        Calendar c = Calendar.getInstance();
        System.out.println("time: " + time); // 18:12:32
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.MILLISECOND, 0);
        System.out.println("date: " + c.getTime()); // Fri Apr 03 00:00:00 CEST 2009
        Timestamp timestamp = new Timestamp( c.getTimeInMillis() + time.getTime() );
        Date d = new Date(timestamp.getTime() );
        System.out.println("\nresult: " + d); // result: Fri Apr 03 17:12:32 CEST 2009If I assume that getting and setting the milis always deals with timezone independent values, but operating methods
like toString(), getHour() etc use the timezone, then I can not explain the result (last line): 17:12:32 is the timezone
independend value. Should'nt d.toString() show the timezone dependend value of 18:12:32?

Similar Messages

  • Create table dinamically using java sql types?

    Hi! I've an application that reads an XML file. This file contains de definitions of some tables, using java sql types. For example:
    <dbtable>
      <dbtablename>Name of table</dbtablename>
      <dbtablefield>
        <name>Name of table field</name>
        <type>java.sql.Types.VARCHAR</type>
        <length>10</lenght>
        <canNull>0</canNull>
        <isPK>1</isPK>
      </dbtablefield>
    </dbtable>That's a little example of one table, with one field. Is a java.sql.Types.VARCHAR (or is equivalent in int), which has a size of 10, it cannot be null and is a primary key for the table.
    Now, the lenght, null, and primary keys are not problem at all. What I want to know, is how do I create de table using the java.sql.Types. I mean, I don't want to hard code:
    String s = "CREATE TABLE name (COLUMN VARCHAR(10)...";Instead, I want to use some "wild cards", as are used in PreparedStatement. The idea of this is that no matter what DB I'm using, I must always be capable of creating the tables not worrying for the DB. I mean, I must be able to create the table in Oracle, SQL Server, DB2, etc., using the same XML and the same java class.
    Something like:
    String s = "CREATE TABLE name (COLUMN ? (10)...";
    someobject.setObject(1,java.sql.Types.VARCHAR);
    someobject.execute(); //create tableIs this possible? Or do I have to make a map for each DB?
    Thanks a lot for your help! Dukes available!

    you can provide some fields at runtime..
    for example
    "CREATE TABLE name (COLUMN" + arg[1] +"(10)..."
    here arg is the string array passed into the main.

  • Using oracle.sql.STRUCT to pass in a COMPLEX OBJECT

    I need to pass in a complex object (object with nested array of objects) into a oracle stored procedure.
    We are using JDBC 9.2.0.1 drivers...
    Note i am able to retrieve a complex object successfully using an oracle struct however i am not able to pass in the struct.
    I do not want to use JPublisher as we are not using SQLJ.
    I have looked through the documentation on using default structs and am getting an error when i try and create the struct...
    I have created an array of objects with a sub array
    and i create a struct descriptor however when i create the actual oracle struct
    like
    oracle.sql.Struct = new oracle.sql.Struct( structDesc,conn,complexobject)
    I get a "java.sql.SQLException: Internal Error: Unable to resolve name"
    Do i have to create STRUCTS for the nested object first ?
    And then nest that STRUCT within the PARENT STRUCT to pass in complex objects ???
    Any help would be much appreciated...
    Gurinder
    email [email protected]

    Thanks Konstantin Goryachev!
    I'm using Oracle JDBC 9.2.0.3 drivers using a SQLData implementation.
    Unfortunately i have something very similar to your code and i still get the following error
    EXC: testPolicyRate(): java.sql.SQLException: Internal Error: Inconsistent catalog view
    java.sql.SQLException: Internal Error: Inconsistent catalog view
         void oracle.jdbc.dbaccess.DBError.throwSqlException(java.lang.String, java.lang.String, int)
              DBError.java:187
         void oracle.jdbc.dbaccess.DBError.throwSqlException(int, java.lang.Object)
              DBError.java:229
         void oracle.sql.StructDescriptor.initMetaData1_9_0()
              StructDescriptor.java:897
         void oracle.sql.StructDescriptor.initMetaData1()
              StructDescriptor.java:864
         boolean oracle.sql.StructDescriptor.isInstantiable()
              StructDescriptor.java:508
         void oracle.sql.STRUCT.<init>(oracle.sql.StructDescriptor, java.sql.Connection, java.lang.Object[])
              STRUCT.java:107
         oracle.sql.STRUCT oracle.sql.OracleSQLOutput.getSTRUCT()
              OracleSQLOutput.java:96
         oracle.sql.STRUCT oracle.sql.STRUCT.toSTRUCT(java.lang.Object, oracle.jdbc.OracleConnection)
              STRUCT.java:408
         oracle.sql.Datum oracle.jdbc.oracore.OracleTypeADT.toDatum(java.lang.Object, oracle.jdbc.driver.OracleConnection)
              OracleTypeADT.java:284
         oracle.sql.Datum[] oracle.jdbc.oracore.OracleTypeADT.toDatumArray(java.lang.Object, oracle.jdbc.driver.OracleConnection, long, int)
              OracleTypeADT.java:327
         oracle.sql.Datum[] oracle.jdbc.oracore.OracleTypeUPT.toDatumArray(java.lang.Object, oracle.jdbc.driver.OracleConnection, long, int)
              OracleTypeUPT.java:143
         oracle.sql.Datum[] oracle.sql.ArrayDescriptor.toOracleArray(java.lang.Object, long, int)
              ArrayDescriptor.java:771
         void oracle.sql.ARRAY.<init>(oracle.sql.ArrayDescriptor, java.sql.Connection, java.lang.Object)
              ARRAY.java:118
         void com.tu.lib.busobject.PolicyRate.main(java.lang.String[])
              PolicyRate.java:198
    Process exited with exit code 0.
    Here's my code
    * Main Method
    public static void main(String[] args)
    throws SQLException, IOException
    Connection conn = null;
    OracleCallableStatement cstmt = null;
    try {
    /* Setup connection */
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    conn = DriverManager.getConnection("jdbc:oracle:thin:@neptune:1521:tu_test", "OPS$WWW", "welcome1");
    conn.setAutoCommit(false);
    System.out.println("conn is open = " + !conn.isClosed());
    /* Setup map */
    System.out.println("Creating type maps...");
    java.util.Map typeMap = conn.getTypeMap();
    typeMap.put(_SQL_NAME,PolicyRate.class);
    typeMap.put(CoverageRate._SQL_NAME, CoverageRate.class);
    typeMap.put(CoverageRate._SQL_ARRAY_NAME,CoverageRate[].class);
    conn.setTypeMap(typeMap);
    /* Create a coverage rate object to be inserted into array of policy rate object */
    CoverageRate covrObj = new CoverageRate(1,
    "HMS",
    30,
    5,
    new BigDecimal(0),
    null,
    null,
    new BigDecimal(0),
    new BigDecimal(0),
    0,
    0);
    /* Create an array */
    System.out.println("Creating descriptor...");
    ArrayDescriptor adesc = new ArrayDescriptor(CoverageRate._SQL_ARRAY_NAME,conn);
    System.out.println("Created descriptor!");
    Object [] covrArray = new Object[1];
    covrArray[0] = covrObj;
    System.out.println("Creating oracle array..");
    ARRAY arr = new ARRAY(adesc,conn,covrArray);
    System.out.println("Created array!!");
    /* Create policy rate object */
    PolicyRate prate = new PolicyRate ("TESTTRA",
    "TRS",
    TUDate.convertToSql("2003","08","27"),
    TUDate.convertToSql("2004","06","25"),
    TUDate.convertToSql("2004","06","29"),
    "NEW",
    1,
    new BigDecimal(0),
    new BigDecimal(0),
    null);
    /* Add coverage rate object to array -- assume array only has one element for timebeing */
    System.out.println("Setting arr in policyrate...");
    prate.setRates(arr);
    System.out.println("Creating array.sql.ARRAY for covrObj..");
    prate.setRates(new oracle.sql.ARRAY(adesc,conn,covrObj));
    System.out.println("Created array.sql.ARRAY for covrObj..");
    /* Setup statemenet object */
    cstmt = (OracleCallableStatement) conn.prepareCall("{call dbpckg_rate_obj.p_rate_obj_calc_rate(?)}");
    /* Bind variables to statement */
    System.out.println("Setting policyrate object...");
    cstmt.setObject(1,prate,OracleTypes.STRUCT);
    System.out.println("Registering out object...");
    cstmt.registerOutParameter(1,oracle.jdbc.OracleTypes.STRUCT,PolicyRate._SQL_NAME);
    cstmt.execute();
    /* Retrieve the object back */
    System.out.println("Getting policy rate object back...");
    prate = (PolicyRate) cstmt.getObject(1);
    System.out.println("Object Retrieved " + prate.getProductcode() + " " + prate.getAgentcode());
    /* Close database connection */
    conn.close();
    catch (Exception exc) {
    System.out.println("EXC: testPolicyRate(): " + exc);
    exc.printStackTrace();
    if (conn != null)
    conn.close();
    finally {     
    if (conn != null)
    conn.close();
    I've opened up a tar through metalink hopefully they can help get past this error...:)
    Gurinder

  • Using java.sql.Time: Offset by 1 hour?

    I have a problem understanding the behaviour of the java.sql.Time class. As the following example shows.
    61952000 ms is the Time 17:12:32. If i feed a Time-Object with it and print the time or date I'll get "18:12:32",
    an offset of 1h. But if I use time.getTime(), I get my ms value which equals 17:12:32.
    As my timezone shows, I have a GMT offset of one hour. But why does the getTime() method not calculate
    the timezone offset to the ms?
    Time time = new Time(61952000);
            System.out.println(time.getTime() / 3600 / 1000); // 17 hours
            System.out.println( new Date(time.getTime()) ); // Thu Jan 01 18:12:32 CET 1970
            System.out.println(time.getTime()); // 61952000
            System.out.println(time); // 18:12:32
            System.out.println(Calendar.getInstance().getTimeZone());
             *  sun.util.calendar.ZoneInfo[id="Europe/Berlin",offset=3600000,dstSavings=3600000,
             *  useDaylight=true,transitions=143,lastRule=java.util.SimpleTimeZone[id=Europe/Berlin,
             *  offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,
             *  startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,
             *  endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]]
             */

    Thanks for your reply. But please take a look at the following code snippet. It intends to add a Timestamp representing the
    start of a day (time component 00:00:00) to a time component (having Date to 01-01-1970):
            Time time = new Time(61952000);
            Calendar c = Calendar.getInstance();
            System.out.println("time: " + time); // 18:12:32
            c.set(Calendar.HOUR_OF_DAY, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.MILLISECOND, 0);
            System.out.println("date: " + c.getTime()); // Fri Apr 03 00:00:00 CEST 2009
            Timestamp timestamp = new Timestamp( c.getTimeInMillis() + time.getTime() );
            Date d = new Date(timestamp.getTime() );
            System.out.println("\nresult: " + d); // result: Fri Apr 03 17:12:32 CEST 2009If I assume that getting and setting the milis always deals with timezone independent values, but operating methods
    like toString(), getHour() etc use the timezone, then I can not explain the result (last line): 17:12:32 is the timezone
    independend value. Should'nt d.toString() show the timezone dependend value of 18:12:32?

  • How to use java.sql.Date ?

    hi there:
    I used
    ps.setDate(27, new java.sql.Date(new java.util.Date().getTime()));
    ps.executeUpdate();
    in my code to insert the current date to the 27th column of one table, this column's type is DATE, the database is ORACLE. However, I got the error like this one: ORA-01843: not a valid month.
    I think I incorrectly used the java.sql.Date API to cause this error. So anyone can tell me how to use it correctly?
    Thanks for the answers,
    Sway

    Other columns are all VARCHAR2 type;
    The oracle error message indicated that this is a
    date-related one. 27th are the only column using DATE
    So I came to draw my conclusion that the SQL might be
    wrong.Except that if, for example, the date column is actually at index 26 then Oracle might try to convert the string being passed in (at 26) as a date. But it isn't a date. So then oracle is going to throw an exception indicating that something is wrong - like that the month is invalid.

  • Getting the current time using java.sql.Time

    I need to set the current time in a database field. I tried the following code (using my logic) to set the current time. But, I end up getting "Jan 1, 1970" in the time field in the database.
    Here is the code :
    Calendar cal = Calendar.getInstance();
    Java.sql.Time now = java.sql.Time.valueOf(
              cal.get(Calendar.HOUR_OF_DAY) + ":" +
              cal.get(Calendar.MINUTE) + ":" +
              cal.get(Calendar.SECOND));
    What should I do to get the current time in the "now" variable? Right now, it ends up in the database as "Jan 1, 1970".
    Thanx in advance.

    Can you show me the code to do SimpleDateFormat?
    Assuming that I use the following skeleton to get the
    time value from the database, can you show me the
    code for the missing link (so as to display in the
    format "hh:mm:ss") ?
    java.sql.Time timeFromDb =
    obj.getActionTime();
    // The above code gets the "time" field from
    the database into "timeFromDb"
    // Use SimpleDateFormat to display the time
    java.text.SimpleDateFormat sdf = new
    java.text.SimpleDateFormat("hh:mm:ss");
    // Now what do I do with "sdf" and
    "timeFromDb" ?
    // Print out the time value
    System.out.printf("Time is : %s\n",
    .... );Hi,
    I don't know if you want 24h clock or not. This is the pattern for 24h clock.
    "HH:mm:ss"
    You get the text string by calling sdf.format(timeFromDb)
    Kaj

  • Need an information using java.sql in jsp

    I found that there is a 'dataset' like architecture in .NET, is there any 'dataset' like substance in our java, if it is means can you give me some ideas for using it in jsp, give me some example for saving a record in the mysql database. very urgent please,

    KIRUPA_SHANKAR wrote:
    I found that there is a 'dataset' like architecture in .NET, is there any 'dataset' like substance in our java, if it is means can you give me some ideas for using it in jsp, give me some example for saving a record in the mysql database. Shouldn't be doing database stuff in JSPs. Use JSTL and its <sql> tags if you must.
    RowSet might be close. I don't write .NET.
    very urgent please,Not to me.
    %

  • Using Java SQL

    Some help on this would be appreciated.
    Basically I have a program that reads from a list of strings and then performs some 'select' and 'delete' queries (with these string variables) on a sybase database. The problem I have is with the results set and 'getString(n)' class.
    I WILL POST SOME CODE IN A REPLY;
    The class checkVal runs a count on each table and returns true or false.
    If the value is zero that means there are no occurances of this ID
    (Variable label) and therefore do not have to be deleted from the table.
    I had to add the "(labelSource.equals("M_CTP_ID"))" for the tables with a different type of relationship.
    The first select statement gives an integer if you perform the statement from a command window but when I run the class checkVal it gives me 0.
    I've tried everything ( I hope not!!)
    The database is Sysbase.
    I'm using the "com.ddtek.jdbc.sybase.SybaseDriver" driver.
    Brian

    if (labelSource.equals("M_CTP_ID")){
    results = null;
    results = stmt.executeQuery( "select count(*) from " + sourceTable + " where " + labelSource + " = " + "(select M_ID from " + counterpartyField1.getText() + " where M_LABEL = " + label +")");     
    addtoLog("SQL: select count(*) from " + sourceTable + " where " + labelSource + " = " + "(select M_ID from " + counterpartyField1.getText() + " where M_LABEL = " + label +")" + newline, code);
    results.next();
    count = Integer.valueOf(results.getString(1)).intValue();
    else{
    results = null;
    results = stmt.executeQuery("select count(*) from " + sourceTable + " where " + labelSource + " = "+ label);
    addtoLog("SQL: select count(*) from " + sourceTable + " where " + labelSource + " = "+ label + newline, code);
    results.next();
    count = Integer.valueOf(results.getString(1)).intValue();
    }

  • USE OF VARRAY and RECORD object vis-a-vis java.sql package

    Hi Geeks,
    I want to pass an array of java objects to a stored procedure and I will use them for table insertion or updation.
    Say I have a table TASK at DataBase end while the same TASK object is there at JAVA end.
    I want to pass an array of Task objects via my stored proc
    Please guide me how shall I use java.sql.Array and java.sql.SQLDataType etc etc. any mechanism in store!..
    Regards,
    Pratap
    London

    Thanks for you help
    I created the package and I get this error this time:
    javax.servlet.ServletException: bean test not found within scope
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:822)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:755)
         org.apache.jsp.login_jsp._jspService(login_jsp.java:68)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:268)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:277)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:223)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)

  • How to check whether java.sql.Connection has been dropped or not

    Hi,
    How can i check whether the connection is dropped from the database or not by using java.sql.Connection API.
    Thanks

    There's a few ways to check Connections, each with a different use:
    (1) conn.isOpen()
    (2) conn == null
    (3) the last one is a little more involved and adds some overhead. You can run SELECT 1 FROM dual; (Oracle) or SELECT 1 (MSSQL) and check for exceptions.
    The only way to check a connection, as far as I know, is to use it. That said, there must be a better way???

  • Obtaining an oracle.sql.STRUCT through a pooled JDBC connection

    Hello,
    I am using WebLogic Server 10 and and Oracle 10 and I am trying to obtain a vendor-specific oracle.sql.STRUCT from a ResultSet using a pooled connection defined in Weblogic. I need the vendor-specific object, rather than simply the java.sql.Struct implementation, because a third party library requires it.
    What gets returned in the ResultSet is a non-exposed WebLogic wrapper object which implements java.sql.Struct, but which cannot be cast to an oracle.sql.STRUCT. I can use reflection on this object to find and call the getVendorObj() method to obtain the oracle.sql.STRUCT, but this solution is not acceptable because this is not a published API and is not guaranteed not to change in future versions.
    How can I reliably obtain a vendor-specific implementation of java.sql.Struct through a WebLogic connection pool in WebLogic Server 10?
    Thanks for any advice,
    -Dan Schwemlein

    dan schwemlein wrote:
    Joe,
    Thanks again. With your guidance, I have arrived at the following approach, which I'll post for the benefit of others, and which I'd be thankful if you would validate:
    1) Import the jar com.bea.core.datasource-1.0.0.0.jar from %BEA_HOME%\modules, which is the only location of the class WLConnection, which is the only class with the getVendorConnection() method you refer to.
    2) Get the logical connection from the pooled data source, cast it to a WLConnection, call getVendorConnection() to obtain an OracleConnection (from the ojdbc jar), and use this connection to obtain the required oracle.sql.STRUCT from an OracleResultSet.
    3) Be aware of the limitations and follow the guidelines in the document http://e-docs.bea.com/wls/docs81/jdbc/thirdparty.html#1043646 regarding security, error handling, releasing resources (close only the logical connection), etc.
    Does this sound like the approach you had in mind?
    Thanks again,
    -Danyes.
    Joe
    >
    Re: Obtaining an oracle.sql.STRUCT through a pooled JDBC connection
    Posted: Jul 16, 2007 3:21 PM
    dan schwemlein wrote:
    Thanks for the quick response!I was working today...
    Thank you for the information about the connection being closed.
    I will look into using this configuration setting.
    You say that you can describe a way to get a handle on an unwrapped
    pool object using some documented WLS-specific code. Are you referring
    here to the getVendorConnection() method?yes.
    This method does not help me
    get the oracle.sql.STRUCT object, because even the connection returned
    by getVendorConnection() returns a wrapped WL java.sql.Struct object
    from a call to getObject().I don't believe it. If you are running in WLS, with a local pool,
    the getVendorConnection() will give you the Oracle connection,
    which will give you an Oracle statement, etc, down to an oracle
    STRUCT object. Once you have a direct reference to the oracle connection,
    we're not in the picture when it returns something to you.
    It would be great if getVendorObj() were
    documented and could be counted on in future versions. To use this
    method, one would still have to access it via Java reflection, because
    the wrapper class and its getVendorObj() method would be exposed in an
    API, correct? Could this method be exposed in the API, so that reflection
    doesn't need to be used, or it is exposed somewhere that isn't documented?getVendorObj() is not yet exposed or therefore supported for the general
    wrapped object, so you would have to start from the connection and
    derive all subobjects from it.
    Thanks again,
    -Dan Schwemlein
    Hello,
    I am using WebLogic Server 10 and and Oracle 10 and I am trying to obtain a
    vendor-specific oracle.sql.STRUCT from a ResultSet using a pooled connection
    defined in Weblogic. I need the vendor-specific object, rather than simply
    the java.sql.Struct implementation, because a third party library requires it.
    What gets returned in the ResultSet is a non-exposed WebLogic wrapper object
    which implements java.sql.Struct, but which cannot be cast to an oracle.sql.STRUCT.
    I can use reflection on this object to find and call the getVendorObj() method to
    obtain the oracle.sql.STRUCT, but this solution is not acceptable because this is
    not a published API and is not guaranteed not to change in future versions.Understood. We all benefit from sticking to the J2EE standards,
    but we could also wish Oracle had done so with it's driver objects.
    I will assume your code is running in the WebLogic server, because
    an external JVM can never access the real driver object, which will
    always really be in the WLS JVM. No active JDBC object is serializable.
    How can I reliably obtain a vendor-specific implementation of java.sql.Struct
    through a WebLogic connection pool in WebLogic Server 10?There is no way to get a handle on an unwrapped pool object without using some
    WLS-specific code, though I can describe a way with documented methods,
    and/or I can get our documentation altered to say we'll support the
    getVendorObj() method. We introspect every vendor object, and for those
    implementations that have done the wise thing, projecting any non-standard
    methods as an Interface, we are able to also project that Interface so
    the vndor example code should work. However, in some poorly-done
    cases, such as for some Oracle stuff, there is either no Interface,
    or the Oracle code has extensions that take java.sql objects as input,
    (at least that's the signature of the method) but two lines into the
    method, the Oracle code assumes and casts the java.sql object to a concrete
    Oracle object. In these use cases you need the direct unwrapped object.
    We provide and document Connection.getVendorConnection(), and intend
    getVendorObj() to serve the same for subobjects, but note the dangers
    and responsibilities: We rely on our wrappers to implement the security
    and thread-safety of our pooling system. Because user code can get
    unrestricted access to the actual connection from most JDBC objects,
    we can never trust that we have complete control once a vendor object
    is exposed. Therefore, by default we will close and replace every JDBC
    connection so exposed, as soon as the current thread is finished with
    the pool connection. This hurts performance. We also document a pool
    config setting that will tell us that you take responsibility for any such
    problems, and not to close connections just because they've been exposed.
    HTH,
    Joe
    Thanks for any advice,
    -Dan Schwemlein

  • 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

  • Usage of java.sql.Timestamp with classes12.zip and ojdbc14.jar  ?

    Hi all,
    If i'm using java.sql.Timestamp with classes12 it is functioning perfectly,
    if i'm using ojdbc14 and java.sql.Timestamp it is functioning in different way and failing to do the action..
    Example : update set xxx=yy where time = my Timestamp object set in Prepared statement
    Hope to see the answer

    http://forum.java.sun.com/thread.jspa?threadID=460615&messageID=2116517
    Timestamp insert problem
    Using the "classes12.zip" file that comes with the distribution for Oracle versions 8.1.6.x and 8.1.7.x, Oracle's DATE datatype is mapped to the "java.sql.Timestamp" class. However, the "ojdbc14.jar" driver maps DATE to "java.sql.Date", and "java.sql.Date" only holds a date (without a time), whereas "java.sql.Timestamp" holds both a date and a time.

  • Java.sql.PreparedStatement#setUnicodeStream deprecated

    Hi all!
    The method setUnicodeStream of java.sql.PreparedStatement is set to deprecated without any comment since at least J2SE 1.3.1. Does anybody know what's the reason? Is there any alternative?
    Thanks in advance
    Carsten

    I've got a java.sql.date that I need to put into a
    calendar object. I was planning to use
    Calendar.set(date.getYear(), date.getMonth(),
    date.getDay()) but these methods are all deprecated
    now. Do I have to do date.toString() first, then
    parse out each value? This seems like a waste to me.
    btw - we use java.sql.date for our DB dates.What about Calendar.setTime(Date date)?

  • Problem saving java.sql.timestamp

    I am using java.sql.timestamps for all date fields inside the database.
    the client program is using a session bean to insert the data into the database. Afterwards when I do a select in sql plus the date is always 2 hours and 30 minutes above the value I supplied to the database.
    Are there any timezone settings I have to supply on the server ?
    thx in advance
    null

    Please shrink your code down to the bare minimum that compiles and demonstrates the problem. Do not include any tests that pass. Just the one that fails, and describe clearly exactly how it fails--what's expected and what is observed instead.
    You can probably even get rid of the separate test class and just put it all in main, or at least all in the same class with main and one or a small handful of other methods.

Maybe you are looking for

  • Question about terms of payment of company code tab of customer master data

    Hi: As I know there are two places to be maintained terms of payment of customer master data, one is in billing documents of sales area data tab and I understood it will default to the one in sales order when you create, another is in company code ta

  • In macro call method of object

    Hi, is it possible to call method provides in parameter to macro ? From the call of my macro i provide object instancied and the name of my method. In my macro i wanted to do : CALL METHOD &1->&2 but it don't work. I provided you my code which does n

  • Oracle 10g installation guidance

    hi every body i am a newbie and a student. i have EBS 12R installed over my laptop - win Xp platform. now i want to install oracle 10 over linux platform ... for that i am going to install "ORACLE ENTERPRISE LINUX" 1st and then oracle 10g over my lap

  • Why does Skype not work with mavericks?

    I recently "upgraded" to Mavericks and find that several of my other applications no longer work...Great "UPGRADE" I think I know why it was offered FREE.

  • Mac pro webcam is not working

    My mac book pro web cam isn't working... the green light turns on, but no picture. Help!!