GetUpdateCount()

I have got one problem with Oracle Driver. As per the documents if I am executing getUpdateCount() two times & I know I execute method will return only one time updateCount then if I am calling getUpdateCount() second time it returns me the same value as during the first time execution.
I studied various material for ex.
5.1.3 Using the Method Execute
The execute method should be used only when it is possible that a statement may return more than one ResultSet object, more than one update count, or a combination of ResultSet objects and update counts. These multiple possibilities for results, though rare, are possible when one is executing certain stored procedures or dynamically executing an unknown SQL string (that is, unknown to the application programmer at compile time). For example, a user might execute a stored procedure (using a CallableStatement object-see Section 8, "CallableStatement," of this JDBC Guide), and that stored procedure could perform an update, then a select, then an update, then a select, and so on. Typically someone using a stored procedure will know what it returns.
Because the method execute handles the cases that are out of the ordinary, it is no surprise that retrieving its results requires some special handling. For instance, suppose it is known that a procedure returns two result sets. After using the method execute to execute the procedure, one must call the method getResultSet to get the first result set and then the appropriate getXXX methods to retrieve values from it. To get the second result set, one needs to call getMoreResults and then getResultSet a second time. If it is known that a procedure returns an update count, the method getUpdateCount is called.
Those cases where one does not know what will be returned are more complicated. The method execute returns true if the result is a ResultSet object and false if it is a Java int. If it returns an int, that means that the result is either an update count or that the statement executed was a DDL command. The first thing to do after calling the method execute, is to call either getResultSet or getUpdateCount. The method getResultSet is called to get what might be the first of two or more ResultSet objects; the method getUpdateCount is called to get what might be the first of two or more update counts.
When the result of an SQL statement is not a result set, the method getResultSet will return null. This can mean that the result is an update count or that there are no more results. The only way to find out what the null really means in this case is to call the method getUpdateCount, which will return an integer. This integer will be the number of rows affected by the calling statement or -1 to indicate either that the result is a result set or that there are no results. If the method getResultSet has already returned null, which means that the result is not a ResultSet object, then a return value of -1 has to mean that there are no more results. In other words, there are no results (or no more results) when the following is true:
((stmt.getResultSet() == null) && (stmt.getUpdateCount() == -1))
If one has called the method getResultSet and processed the ResultSet object it returned, it is necessary to call the method getMoreResults to see if there is another result set or update count. If getMoreResults returns true, then one needs to again call getResultSet to actually retrieve the next result set. As already stated above, if getResultSet returns null, one has to call getUpdateCount to find out whether null means that the result is an update count or that there are no more results.
Here as per this I should get -1 during the second time execution but with Oracle it is not. why? Is there any fix for this?

Becuase you are calling getUpdateCount() twice, while condition and trace.

Similar Messages

  • Statement.getUpdateCount() is not working

    Hi
    I'm using the Thin driver, and getUpdateCount() is never returning -1, no matter how many times I do a getMoreResults()
    Thus I can't be sure if all results have been read.
    HELP!!
    null

    I'm having the same problem with both the Thin and OCI JDBC drivers in Oracle 8i 8.1.6. Any help on this would be greatly appreciated.
    I have a while loop that generically checks for update counts and result sets after calling the execute function of a Statement object. As the person stated below, getUpdateCount never returns a -1 and I get into an infinite loop. I am using the getUpdateCount, getResultSet and getMoreResults methods in conjunction with the execute method.
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Marcos Scriven ([email protected]):
    Hi
    I'm using the Thin driver, and getUpdateCount() is never returning -1, no matter how many times I do a getMoreResults()
    Thus I can't be sure if all results have been read.
    HELP!!<HR></BLOCKQUOTE>
    null

  • Problem in getting correct update records count while getUpdateCount()

    hi,
    I have used "Select in Insert" queries for migrating data from one table to another.
    like
    INSERT INTO TABLE1 (COL1, COL2)
    SELECT COL1,COL2,... FROM TABLE2
    WHERE COL1 = ... AND COL2 = ...;
    Case 1:
    I added these statements as addBatch() & at the end i execute method " executeBatch()".
    Then i execute
    getUpdateCount() method
    on that prepareStatement ,but that count was not correct all the time.
    Case 2:
    If i run the same code with executeUpdate() method , it returned me the correct number of records counts that are inserted into the table.
    I cudn't able to understand that it is failing for case1.
    Can anybody tell the reason for this behaviour .......................
    Edited by: user11187328 on Mar 18, 2010 4:52 AM

    hi,
    Thanks again for a correct reply but can u also tell me tht which jar i needs to included.
    There are so many jar files & should i remove old jar files or jvm auto picks the updated jar file.
    Following jar files are shown on the link:::
    ojdbc5.jar (1,996,228 bytes) - Classes for use with JDK 1.5. It contains the JDBC driver classes, except classes for NLS support in Oracle Object and Collection types.
    ojdbc5_g.jar (3,081,328 bytes) - Same as ojdbc5.jar, except that classes were compiled with "javac -g" and contain tracing code.
    ojdbc6.jar (2,111,220 bytes) - Classes for use with JDK 1.6. It contains the JDBC driver classes except classes for NLS support in Oracle Object and Collection types.
    ojdbc6_g.jar (3,401,519 bytes) - Same as ojdbc6.jar except compiled with "javac -g" and contains tracing code.
    ojdbc5dms.jar (2,429,777 bytes) - Same as ojdbc5.jar, except that it contains instrumentation to support DMS and limited java.util.logging calls.
    ojdbc5dms_g.jar (3,101,875 bytes) - Same as ojdbc5_g.jar, except that it contains instrumentation to support DMS.
    ojdbc6dms.jar (2,655,741 bytes) - Same as ojdbc6.jar, except that it contains instrumentation to support DMS and limited java.util.logging calls.
    ojdbc6dms_g.jar (3,423,263 bytes) - Same as ojdbc6_g.jar except that it contains instrumentation to support DMS.
    orai18n.jar (1,656,280 bytes) - NLS classes for use with JDK 1.5, and 1.6. It contains classes for NLS support in Oracle Object and Collection types. This jar file replaces the old nls_charset jar/zip files.
    demo.zip (603,363 bytes) - contains sample JDBC programs.

  • Bug in getUpdateCount using Oracle

    getUpdateCount() dos not return the right value (-1) when invoked for the second time.
    I wrote the following piece of code to "dynamically execute an unknown SQL string".
    According to the documentation the code is OK.
    I use a stmt that does either an insert, update or delete.
    When I run it with Sybase it works fine, the second time I invoke getUpdateCount() it returns -1, indicating there are no more updates counts (nor resultsets).
    In the case of Oracle, the getUpdateCount keeps returning the original value and the program enters an infinite loop.
    Can anybody help me with this?
    Maybe is the version of the Oracle interface I am using (java12.zip as it comes with the package).
    The code is:
    String sqlStmt = "delete from table...";
    // con was already created and is ok, because all selects
    // work fine
    // DRIVER = oracle.jdbc.driver.OracleDriver
    // URL = jdbc:oracle:thin:@xx.xx.xx.xx:3521:orasd99
    stmt = con.createStatement();
    int guc = 0;
    boolean esResult = stmt.execute(sqlStmt);
    try {
    while (true) {
    if (esResult) {
    ResultSet rs = stmt.getResultSet();
    procesarResultSet(rs); // just process the rs
    else {
    guc = stmt.getUpdateCount();
    if (!esResult && (guc == -1)) break;
    esResult = stmt.getMoreResults();
    Thanks in advance for any tip.
    Ag~

    "delete from table" doesn't return a result set.
    From the documentation for getUpdateCount()
    "if the result is a ResultSet object or there are no more results, -1 is returned."
    Presumably you are using this because the SQL you are using could have more than one result set. -1 is returned in two cases:
    -No more results
    -The result is a ResultSet (a query.)
    Personally I wouldn't rely on 'update counts' from JDBC for anything. The methods are not vital to the functioning of the interface and consequently they simply might not return the correct value. If you want an accurate count use a stored procedure.

  • BatchUpdateException.getUpdateCounts() problem

    When error ouccurs using statement.addbatch() and statement.executeBatch() in JDBC 2.0, I want to see how many statements are sucessfully excuted and at what point the error ouccured. So I used BatchUpdateException.getUpdateCount(). however, in the int[] returned, all elements contain -3, which is flag for EXECUTION_FAILED. this int[] supposed to have either the affected line number for each statements, or a -2, the SUCESS_NO_INFO for the all suceesed statements, and have -3 for all failed ones.
    please help

    I agree. I am in the same dilemma. I really need to know which one failed in the batch. I think oracle is not in compliance with the JDBC specs.

  • MySQL and Java - getting program to work

    I am setting up mysql to run sql from a Java program on my pc at home and probably biting off more than I can chew. I get these messages when executing the java program ExecuteSQL.java:
    Exception in thread "main" java.lang.NoClassDefFoundError: Test2 <wrong name: MyProjects/test2/Test2>
    at java.lang.ClassLoader.defineClass0<Native Method>
    at java.lang.ClassLoader.defineClass<Unknown Source>
    at java.security.SecurityClassLoader.defineClass<Unknown Source>
    at java.net.URLClassLoader.defineClass<Unknown Source>
    at java.net.URLClassLoader.access$100<Unknown Source>
    at java.net.URLClassLoader$1.run<Unknown Source>
    at java.security.AccessController.ddPrivileged<Native Method>
    at java.lang.ClassLoader.findClass<Unknown Source>
    at java.lang.ClassLoader.loadClass<Unknown Source>
    at sun.misc.Launcher$AppClassLoader.loadClass<Unknown Source>
    at java.lang.ClassLoader.loadClass<Unknown Source>
    at java.lang.ClassLoader.loadClassInternal<Unknown Source>
    This is what I did.
    I created a folder on my C: drive named MySQL.
    I downloaded these two zip files form the MySQL website
         * mysql-connector-java-3.0.11-stable
         * mysql-4.0.18-win.zip
    Installed both of these in folder MySQL.
    I modified this line in the program ("ExecuteSQL" 1st pgm in chapter 17) I got from "Java Examples In a Nutshell" and compiled it into directory jwork.
    String driver = "com.mysql.jdbc.driver", url = "jdbc:mysql://", user = "", password = "";
    The readme file talks about putting a jar file in $JAVA_HOME/jre/lib/ext.
    the word "Java_Home" (I now know) is not literally the name but represents the
    name of the folder where the JDK to be used exists. So I put a copy of
    mysql-connector-java-3.0.11-stable-bin.jar in folder C:\JDK14/jre/lib/ext.
    Then I get a ClassNotFoundException error com.mysql.jdbc.driver.
    After finding
    http://forum.java.sun.com/thread.jsp?forum=31&thread=439796
    and
    http://forum.java.sun.com/thread.jsp?forum=31&thread=499888
    and others, I copied (a second copy) the jar file to the directory where I am create my java objects.
    Then I unzipped it to that directory, creating three folders that hold the unzipped objects.
    I tried executing the program again. I get the messages at the top of this post.
    The Manifest file is in one of the three folders unzipped to my java work directory.
    In the second of the two above threads, jsalonen says:
    the problem can be solved by mentioning mysql.jar in the Class-Path attribute
    in the manifest of the jar file:
    In this "manifest" file, there are only three lines and I added a fourth and it looks like this
    (there are two, one in directory MySQL\META-INF and one in directory jwork\META-INF:
    Manifest-Version: 1.0
    Ant-Version: Apache Ant 1.6.1
    Created-By: 1.4.0_01-b03 (Sun Microsystems Inc.)
    Main-Class:jwork\ExecuteSQL
    How do I "mention" mysql.jar in the class path attribute?
    In the index.list file (in the directory with the manifest file, do I need to add anything to refer that "com.mysql.jdbc.driver" is the driver?
    Do I need index.list in MySQL\META-INF ?
    Thank you for your help. The program ExecuteSQL follows.
    * Copyright (c) 2000 David Flanagan. All rights reserved.
    * This code is from the book Java Examples in a Nutshell, 2nd Edition.
    * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
    * You may study, use, and modify it for any non-commercial purpose.
    * You may distribute it non-commercially as long as you retain this notice.
    * For a commercial use license, or to purchase the book (recommended),
    * visit http://www.davidflanagan.com/javaexamples2.
    /** package com.davidflanagan.examples.sql; */
    import java.sql.*;
    import java.io.*;
    * A general-purpose SQL interpreter program.
    public class ExecuteSQL {
    public static void main(String[] args) {
    Connection conn = null; // Our JDBC connection to the database server
    try {
    String driver = "com.mysql.jdbc.driver", url = "jdbc:mysql://",
    user = "", password = "";
    // Parse all the command-line arguments
    for(int n = 0; n < args.length; n++) {
    if (args[n].equals("-d")) driver = args[++n];
    else if (args[n].equals("-u")) user = args[++n];
    else if (args[n].equals("-p")) password = args[++n];
    else if (url == null) url = args[n];
    else throw new IllegalArgumentException("Unknown argument.");
    // The only required argument is the database URL.
    if (url == null)
    throw new IllegalArgumentException("No database specified");
    // If the user specified the classname for the DB driver, load
    // that class dynamically. This gives the driver the opportunity
    // to register itself with the DriverManager.
    if (driver != null) Class.forName(driver);
    // Now open a connection the specified database, using the
    // user-specified username and password, if any. The driver
    // manager will try all of the DB drivers it knows about to try to
    // parse the URL and connect to the DB server.
    conn = DriverManager.getConnection(url, user, password);
    // Now create the statement object we'll use to talk to the DB
    Statement s = conn.createStatement();
    // Get a stream to read from the console
    BufferedReader in =
              new BufferedReader(new InputStreamReader(System.in));
    // Loop forever, reading the user's queries and executing them
    while(true) {
    System.out.print("sql> "); // prompt the user
    System.out.flush(); // make the prompt appear now.
    String sql = in.readLine(); // get a line of input from user
    // Quit when the user types "quit".
    if ((sql == null) || sql.equals("quit")) break;
    // Ignore blank lines
    if (sql.length() == 0) continue;
    // Now, execute the user's line of SQL and display results.
    try {
    // We don't know if this is a query or some kind of
    // update, so we use execute() instead of executeQuery()
    // or executeUpdate() If the return value is true, it was
    // a query, else an update.
    boolean status = s.execute(sql);
              // Some complex SQL queries can return more than one set
              // of results, so loop until there are no more results
    do {
    if (status) { // it was a query and returns a ResultSet
    ResultSet rs = s.getResultSet(); // Get results
    printResultsTable(rs, System.out); // Display them
    else {
    // If the SQL command that was executed was some
    // kind of update rather than a query, then it
    // doesn't return a ResultSet. Instead, we just
    // print the number of rows that were affected.
    int numUpdates = s.getUpdateCount();
    System.out.println("Ok. " + numUpdates +
                             " rows affected.");
    // Now go see if there are even more results, and
    // continue the results display loop if there are.
    status = s.getMoreResults();
    } while(status || s.getUpdateCount() != -1);
    // If a SQLException is thrown, display an error message.
    // Note that SQLExceptions can have a general message and a
    // DB-specific message returned by getSQLState()
    catch (SQLException e) {
    System.err.println("SQLException: " + e.getMessage()+ ":" +
                        e.getSQLState());
    // Each time through this loop, check to see if there were any
    // warnings. Note that there can be a whole chain of warnings.
    finally { // print out any warnings that occurred
              SQLWarning w;
    for(w=conn.getWarnings(); w != null; w=w.getNextWarning())
    System.err.println("WARNING: " + w.getMessage() +
                             ":" + w.getSQLState());
    // Handle exceptions that occur during argument parsing, database
    // connection setup, etc. For SQLExceptions, print the details.
    catch (Exception e) {
    System.err.println(e);
    if (e instanceof SQLException)
    System.err.println("SQL State: " +
                        ((SQLException)e).getSQLState());
    System.err.println("Usage: java ExecuteSQL [-d <driver>] " +
                   "[-u <user>] [-p <password>] <database URL>");
    // Be sure to always close the database connection when we exit,
    // whether we exit because the user types 'quit' or because of an
    // exception thrown while setting things up. Closing this connection
    // also implicitly closes any open statements and result sets
    // associated with it.
    finally {
    try { conn.close(); } catch (Exception e) {}
    * This method attempts to output the contents of a ResultSet in a
    * textual table. It relies on the ResultSetMetaData class, but a fair
    * bit of the code is simple string manipulation.
    static void printResultsTable(ResultSet rs, OutputStream output)
         throws SQLException
    // Set up the output stream
    PrintWriter out = new PrintWriter(output);
    // Get some "meta data" (column names, etc.) about the results
    ResultSetMetaData metadata = rs.getMetaData();
    // Variables to hold important data about the table to be displayed
    int numcols = metadata.getColumnCount(); // how many columns
    String[] labels = new String[numcols]; // the column labels
    int[] colwidths = new int[numcols]; // the width of each
    int[] colpos = new int[numcols]; // start position of each
    int linewidth; // total width of table
    // Figure out how wide the columns are, where each one begins,
    // how wide each row of the table will be, etc.
    linewidth = 1; // for the initial '|'.
    for(int i = 0; i < numcols; i++) {             // for each column
    colpos[i] = linewidth; // save its position
    labels[i] = metadata.getColumnLabel(i+1); // get its label
    // Get the column width. If the db doesn't report one, guess
    // 30 characters. Then check the length of the label, and use
    // it if it is larger than the column width
    int size = metadata.getColumnDisplaySize(i+1);
    if (size == -1) size = 30; // Some drivers return -1...
         if (size > 500) size = 30; // Don't allow unreasonable sizes
    int labelsize = labels.length();
    if (labelsize > size) size = labelsize;
    colwidths[i] = size + 1; // save the column the size
    linewidth += colwidths[i] + 2; // increment total size
    // Create a horizontal divider line we use in the table.
    // Also create a blank line that is the initial value of each
    // line of the table
    StringBuffer divider = new StringBuffer(linewidth);
    StringBuffer blankline = new StringBuffer(linewidth);
    for(int i = 0; i < linewidth; i++) {
    divider.insert(i, '-');
    blankline.insert(i, " ");
    // Put special marks in the divider line at the column positions
    for(int i=0; i<numcols; i++) divider.setCharAt(colpos[i]-1,'+');
    divider.setCharAt(linewidth-1, '+');
    // Begin the table output with a divider line
    out.println(divider);
    // The next line of the table contains the column labels.
    // Begin with a blank line, and put the column names and column
    // divider characters "|" into it. overwrite() is defined below.
    StringBuffer line = new StringBuffer(blankline.toString());
    line.setCharAt(0, '|');
    for(int i = 0; i < numcols; i++) {
    int pos = colpos[i] + 1 + (colwidths[i]-labels[i].length())/2;
    overwrite(line, pos, labels[i]);
    overwrite(line, colpos[i] + colwidths[i], " |");
    // Then output the line of column labels and another divider
    out.println(line);
    out.println(divider);
    // Now, output the table data. Loop through the ResultSet, using
    // the next() method to get the rows one at a time. Obtain the
    // value of each column with getObject(), and output it, much as
    // we did for the column labels above.
    while(rs.next()) {
    line = new StringBuffer(blankline.toString());
    line.setCharAt(0, '|');
    for(int i = 0; i < numcols; i++) {
    Object value = rs.getObject(i+1);
              if (value != null)
              overwrite(line, colpos[i] + 1, value.toString().trim());
    overwrite(line, colpos[i] + colwidths[i], " |");
    out.println(line);
    // Finally, end the table with one last divider line.
    out.println(divider);
    out.flush();
    /** This utility method is used when printing the table of results */
    static void overwrite(StringBuffer b, int pos, String s) {
    int slen = s.length(); // string length
    int blen = b.length(); // buffer length
    if (pos+slen > blen) slen = blen-pos; // does it fit?
    for(int i = 0; i < slen; i++) // copy string into buffer
    b.setCharAt(pos+i, s.charAt(i));

    Don't put those JARs in the lib/ext directory. Only language extensions (e.g., packages that start with "javax") belong in there.
    Learn how to set the CLASSPATH properly for starters:
    http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/classpath.html
    You might want to look at the JDBC tutorial, too:
    http://java.sun.com/docs/books/tutorial/jdbc/
    Do one thing at a time. Get the program to work, then worry about packaging it into an executable JAR.

  • Plz help me... Applet error...

    Hi... I have a problem... I don't understand... I thing that right... but...
    Error #: 360 : unreported exception:
    java.lang.ClassNotFoundException; must be caught or declared to be
    thrown at line 191, column 23
    --> Class.forName ("net.avenir.jdbc2.Driver");
    Which the error is? ....
    import sql.*;
    void button2_actionPerformed(ActionEvent e) {
    String estructura = "";
    int i = 0;
    String url = "jdbc: AvenirDriver: //http://192.168.0.123:1433/CO_SQL";
    String user = "sa";
    String pass = "";
    String query = "SELECT * FROM TDB";
    System.out.println(query);
    try {
    Class.forName ("net.avenir.jdbc2.Driver");
    DriverManager.setLogStream(System.out);
    Connection con = DriverManager.getConnection (url, user, pass);
    checkForWarning (con.getWarnings ());
    DatabaseMetaData dma = con.getMetaData ();
    Statement stmt = con.createStatement ();
    ResultSet rs = stmt.executeQuery (query);
    ResultSetMetaData rsmd = rs.getMetaData ();
    int numCols = rsmd.getColumnCount ();
    System.out.println(numCols);
    boolean more = rs.next ();
    if (more){
    while (more) {
    for (i=1; i<=numCols; i++) {
    rs.getString(i);
    more = rs.next ();
    catch (SQLException exc) {
    System.out.println(exc);

    Thank you, I have modified the code but doesn't even work...
    I try this...
    public static void CBD() throws IOException,
    java.sql.SQLException,ClassNotFoundException
         String url= "jdbc: AvenirDriver: //192.168.0.123:
    1433/BKCOFF";
         Class.forName ("net.avenir.jdbc2.Driver");
         Connection ctn          = DriverManager.getConnection
    (url,"sa","");
         Statement stmt          = ctn.createStatement();
         boolean moreResult     = stmt.execute("select * from
    TDB");
         int updateCount          = stmt.getUpdateCount();
         ResultSet rst          = null;
         rst = stmt.getResultSet();
         while(rst.next())
              System.out.println(rst.getObject(1));
    void button2_actionPerformed(ActionEvent e){
    int i = 0;
    CBD(); //<--Error #: 360 : unreported exception:
    java.lang.ClassNotFoundException; must be caught or declared to be
    thrown at line 201, column 8

  • To call db2 stored procedure having parameters in java application

    Hi,
    I've created db2 stored procedure which is running perfectly on db2 server after giving a CALL to it. But when I tried to call this same stored procedure in java application, its reflecting with following error......
    com.ibm.db2.jcc.b.SqlException: [jcc][10100][10910][3.50.152] java.sql.CallableStatement.executeQuery() was called but no result set was returned.
    Use java.sql.CallableStatement.executeUpdate() for non-queries. ERRORCODE=-4476, SQLSTATE=null
    at com.ibm.db2.jcc.b.wc.a(wc.java:55)
    at com.ibm.db2.jcc.b.wc.a(wc.java:102)
    at com.ibm.db2.jcc.b.tk.b(tk.java:575)
    at com.ibm.db2.jcc.b.vk.yb(vk.java:136)
    at com.ibm.db2.jcc.b.vk.executeQuery(vk.java:114)
    at SPApplication.main(SPApplication.java:31)
    Here is the code.......
    import java.sql.*; public class SPApplication { public static Connection con; public static CallableStatement proc_stmt; public static ResultSet rs; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { Class.forName("DB2 DRIVER CLASS"); System.out.println("Class loaded....."); con = DriverManager.getConnection("jdbc:db2://localhost:PORTNO/" +                                   " DatabaseName", "username", "password"); System.out.println("Connection established....."); proc_stmt = con.prepareCall("call procedure_name(?)"); //IN Parameter proc_stmt.setInt(1, 5); System.out.println("Called procedure....."); rs = proc_stmt.executeQuery(); /******** THIS IS LINE NO. 31 *********/ while (rs.next()) {                              // Fetching rows one by one over here } proc_stmt.close(); rs.close(); con.close(); } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } catch (SQLException sqle) { sqle.printStackTrace(); } finally { /* try { proc_stmt.close(); rs.close(); con.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } */ } } }
    Please correct me, if I am wrong at any point in my application..
    I would really appreciate for resolving my problem.
    Thanks,
    Manasi N.

    Hi jschell ,
    Firstly, I tried out with execute() and getMoreResults() to check if the statement is returning result set. - Its returning "null" only.
    Secondly, I tried with following one by one :
    1. Find a new jdbc driver
    2. Write a different stored procedure.I am using DB2 Express edition - DB2 v9.7.0.0
    I have the required jar files - i)db2jcc.jar ii) db2jcc_license_cu.jar
    From these I found the available jdbc drivers as -
    i) com.ibm.db2.jcc.DB2Driver
    ii) COM.ibm.db2os390.sqlj.jdbc.DB2SQLJDriver
    iii) com.ibm.db2.jcc.uw.DB2StoredProcDriver
    I tried out my code by using each of these drivers, but still returning result set as null.
    Moreover, I changed my stored procedure which has cursor returning result set. In this case also, result set is null.
    Code snippet for this SP is -
    30             Class.forName("com.ibm.db2.jcc.uw.DB2StoredProcDriver");
    31             System.out.println("Class loaded....");
    32             con = DriverManager.getConnection
    33                 ("jdbc:db2://localhost:portno/dbName", "user", "password");
    34             System.out.println("Connection established....");
    35
    36             proc_stmt = con.prepareCall("call javaSP()");
    37            
    38             System.out.println("Called stored procedure....");
    39            
    40             proc_stmt.execute();
    41             //proc_stmt.executeUpdate();
    42             //rs = proc_stmt.getResultSet();
    43
    44             System.out.println("Query executed....");
    45            
    46             if ((proc_stmt.getMoreResults() == false) &&
    47                     (proc_stmt.getUpdateCount() == -1)) {
    48                 System.out.println("No more result sets");
    49             }o/p is (for every mentioned above jdbc driver) :-
    Class loaded....
    Connection established....
    Called stored procedure....
    Query executed....
    No more result sets..
    The o/p is always "No more result sets"
    What else can be tried out to retrieve the result set from stored procedure from Java application? And the most important, these same stored procedures are returning result sets on db2 server after calling them.
    Thank you,
    Manasi.N
    Edited by: Manasi.N on Apr 14, 2010 12:27 AM
    Edited by: Manasi.N on Apr 14, 2010 12:28 AM

  • Getting Connected for the First Time with JDBC

    Hello everyone. I am trying to make my first database connection to a mysql database with Java. I am using jdk 1.5.0, MySQL 4.1.11 nt, and I think I have the freshly downloaded driver C:\jdk1.5.0\jre\lib\ext\mysql-connector-java-3.0.16-ga-bin.jar" installed in the right spot. When I try to run the following code...
    package dbfinder;
    import java.sql.*;
    import javax.sql.*;
    import com.sun.rowset.JdbcRowSetImpl;
    import javax.sql.rowset.JdbcRowSet;
    import java.sql.ResultSetMetaData;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2005</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class DatabaseConnector {
    public DatabaseConnector() {
    public static void main(String args[]){
    Connection connection;
    Statement statement;
    // ResultSet resultSet;
    // ResultSetMetaData metaData;
    String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
    String DATABASE_URL = "jdbc:mysql://localhost/state_crime";
    String USER = "cis695d";
    String PASSWORD = "cis695d";
    JdbcRowSet rowSet = new JdbcRowSetImpl();
    try {
    Class.forName(DATABASE_DRIVER); // load database driver
    System.out.println("class loaded");
    rowSet.setUrl("DATABASE_URL");
    rowSet.setUsername(USER);
    rowSet.setPassword(PASSWORD);
    rowSet.setCommand("Select * FROM state_crime_rates");
    rowSet.execute();
    ResultSetMetaData metaData = rowSet.getMetaData();
    int numberOfColumns;
    numberOfColumns = metaData.getColumnCount();
    System.out.println(numberOfColumns);
    } catch(SQLException sqlException){
    sqlException.printStackTrace();
    System.exit(1);
    catch(ClassNotFoundException classNotFound){
    classNotFound.printStackTrace();
    System.exit(1);
    I get the following exception...
    java.sql.SQLException: No suitable driver
         at java.sql.DriverManager.getConnection(DriverManager.java:545)
         at java.sql.DriverManager.getConnection(DriverManager.java:171)
         at com.sun.rowset.JdbcRowSetImpl.connect(JdbcRowSetImpl.java:618)
         at com.sun.rowset.JdbcRowSetImpl.prepare(JdbcRowSetImpl.java:630)
         at com.sun.rowset.JdbcRowSetImpl.execute(JdbcRowSetImpl.java:526)
         at dbfinder.DatabaseConnector.main(DatabaseConnector.java:44)
    Does anyone have any ideas? Is it my code? Is there a different driver I should use? Any help would be greatly appreciated.

    Hello everyone. I am trying to make my first
    database connection to a mysql database with Java. I
    am using jdk 1.5.0, MySQL 4.1.11 nt, and I think I
    have the freshly downloaded driver
    C:\jdk1.5.0\jre\lib\ext\mysql-connector-java-3.0.16-ga
    -bin.jar" installed in the right spot. You shouldn't be putting that JAR in jre/lib/ext, even if you've found some docs to tell you to do it. Only language extensions (e.g., packages that begin w/javax) belong there.
    I get the following exception...
    java.sql.SQLException: No suitable driver
    Does anyone have any ideas? Is it my code? Is there
    a different driver I should use? Any help would be
    greatly appreciated.The driver is correct. The class loader found it, even though I think you should use the -classpath option to find the JAR.
    It's your code.
    What are you doing with all that RowSet stuff?
    This works. Study it:
    import java.sql.*;
    import java.util.*;
    * Command line app that allows a user to connect with a database and
    * execute any valid SQL against it
    public class DataConnection
        public static final String DEFAULT_DRIVER   = "sun.jdbc.odbc.JdbcOdbcDriver";
        public static final String DEFAULT_URL      = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\\Edu\\Java\\Forum\\DataConnection.mdb";
        public static final String DEFAULT_USERNAME = "admin";
        public static final String DEFAULT_PASSWORD = "";
        public static final String DEFAULT_DRIVER   = "com.mysql.jdbc.Driver";
        public static final String DEFAULT_URL      = "jdbc:mysql://localhost:3306/hibernate";
        public static final String DEFAULT_USERNAME = "admin";
        public static final String DEFAULT_PASSWORD = "";
        /** Database connection */
        private Connection connection;
         * Driver for the DataConnection
         * @param command line arguments
         * <ol start='0'>
         * <li>SQL query string</li>
         * <li>JDBC driver class</li>
         * <li>database URL</li>
         * <li>username</li>
         * <li>password</li>
         * </ol>
        public static void main(String [] args)
            DataConnection db = null;
            try
                if (args.length > 0)
                    String sql      = args[0];
                    String driver   = ((args.length > 1) ? args[1] : DEFAULT_DRIVER);
                    String url      = ((args.length > 2) ? args[2] : DEFAULT_URL);
                    String username = ((args.length > 3) ? args[3] : DEFAULT_USERNAME);
                    String password = ((args.length > 4) ? args[4] : DEFAULT_PASSWORD);
                    System.out.println("sql     : " + sql);
                    System.out.println("driver  : " + driver);
                    System.out.println("url     : " + url);
                    System.out.println("username: " + username);
                    System.out.println("password: " + password);
                    db = new DataConnection(driver, url, username, password);
                    System.out.println("Connection established");
                    Object result = db.executeSQL(sql);
                    System.out.println(result);
                else
                    System.out.println("Usage: db.DataConnection <sql> <driver> <url> <username> <password>");
            catch (SQLException e)
                System.err.println("SQL error: " + e.getErrorCode());
                System.err.println("SQL state: " + e.getSQLState());
                e.printStackTrace(System.err);
            catch (Exception e)
                e.printStackTrace(System.err);
            finally
                if (db != null)
                    db.close();
                db = null;
         * Create a DataConnection
         * @throws SQLException if the database connection fails
         * @throws ClassNotFoundException if the driver class can't be loaded
        public DataConnection() throws SQLException,ClassNotFoundException
            this(DEFAULT_DRIVER, DEFAULT_URL, DEFAULT_USERNAME, DEFAULT_PASSWORD);
         * Create a DataConnection
         * @throws SQLException if the database connection fails
         * @throws ClassNotFoundException if the driver class can't be loaded
        public DataConnection(final String driver,
                              final String url,
                              final String username,
                              final String password)
            throws SQLException,ClassNotFoundException
            Class.forName(driver);
            this.connection = DriverManager.getConnection(url, username, password);
         * Get Driver properties
         * @param database URL
         * @return list of driver properties
         * @throws SQLException if the query fails
        public List getDriverProperties(final String url)
            throws SQLException
            List driverProperties   = new ArrayList();
            Driver driver           = DriverManager.getDriver(url);
            if (driver != null)
                DriverPropertyInfo[] info = driver.getPropertyInfo(url, null);
                if (info != null)
                    driverProperties    = Arrays.asList(info);
            return driverProperties;
         * Clean up the connection
        public void close()
            close(this.connection);
         * Execute ANY SQL statement
         * @param SQL statement to execute
         * @returns list of row values if a ResultSet is returned,
         * OR an altered row count object if not
         * @throws SQLException if the query fails
        public Object executeSQL(final String sql) throws SQLException
            Object returnValue;
            Statement statement = null;
            ResultSet rs = null;
            try
                statement = this.connection.createStatement();
                boolean hasResultSet    = statement.execute(sql);
                if (hasResultSet)
                    rs                      = statement.getResultSet();
                    ResultSetMetaData meta  = rs.getMetaData();
                    int numColumns          = meta.getColumnCount();
                    List rows               = new ArrayList();
                    while (rs.next())
                        Map thisRow = new LinkedHashMap();
                        for (int i = 1; i <= numColumns; ++i)
                            String columnName   = meta.getColumnName(i);
                            Object value        = rs.getObject(columnName);
                            thisRow.put(columnName, value);
                        rows.add(thisRow);
                    returnValue = rows;
            else
                int updateCount = statement.getUpdateCount();
                returnValue     = new Integer(updateCount);
            finally
                close(rs);
                close(statement);
            return returnValue;
         * Close a database connection
         * @param connection to close
        public static final void close(Connection connection)
            try
                if (connection != null)
                    connection.close();
                    connection = null;
            catch (SQLException e)
                e.printStackTrace();
         * Close a statement
         * @param statement to close
        public static final void close(Statement statement)
            try
                if (statement != null)
                    statement.close();
                    statement = null;
            catch (SQLException e)
                e.printStackTrace();
         * Close a result set
         * @param rs to close
        public static final void close(ResultSet rs)
            try
                if (rs != null)
                    rs.close();
                    rs = null;
            catch (SQLException e)
                e.printStackTrace();
         * Close a database connection and statement
         * @param connection to close
         * @param statement to close
        public static final void close(Connection connection, Statement statement)
            close(statement);
            close(connection);
         * Close a database connection, statement, and result set
         * @param connection to close
         * @param statement to close
         * @param rs to close
        public static final void close(Connection connection,
                                       Statement statement,
                                       ResultSet rs)
            close(rs);
            close(statement);
            close(connection);
    }%

  • Java API for running entire ".sql" files on a remote DB ( mySQL or Oracle)?

    Hi,
    Would anyone happen to know if there's a java API for executing entire ".sql" files (containing several different SQL commands), on a remote database server ?
    It's enough if the API works with MySQL and/or Oracle.
    Just to demonstrate what i'm looking for:
    Suppose you've created sql file "c:/test.sql" with several script lines:
    -- test.sql:
    insert into TABLE1 values(3,3);
    insert into TABLE1 values(5,5);
    create table TABLE2 (name VARCHER) ENGINE innoDB; -- MYSQL specific
    Then the java API should look something like:
    // Dummy java code:
    String driver="com.mysql.jdbc.Driver";
    String url= "jdbc:mysql://localhost:3306/myDb";
    SomeAPI.executeScriptFile( "c:/test.sql", driver, url);
    Thanks.

    No such a API, but it's easy to parse all sqls in a file, then run those command:
    For instance:
    import java.sql.*;
    import java.util.Properties;
    /* A demo show how to load some sql statements. */
    public class testSQL {
    private final static Object[] getSQLStatements(java.util.Vector v) {
    Object[] statements = new Object[v.size()];
    Object temp;
    for (int i = 0; i < v.size(); i++) {
    temp = v.elementAt(i);
    if (temp instanceof java.util.Vector)
    statements[i] = getSQLStatements( (java.util.Vector) temp);
    else
    statements[i] = temp;
    return statements;
    public final static Object[] getSQLStatements(String sqlFile) throws java.
    io.IOException {
    java.util.Vector v = new java.util.Vector(1000);
    try {
    java.io.BufferedReader br = new java.io.BufferedReader(new java.io.
    FileReader(sqlFile));
    java.util.Vector batchs = new java.util.Vector(10);
    String temp;
    while ( (temp = br.readLine()) != null) {
    temp = temp.trim();
    if (temp.length() == 0)
    continue;
    switch (temp.charAt(0)) {
    case '*':
    case '"':
    case '\'':
    // System.out.println(temp);
    break; //Ignore any line which begin with the above character
    case '#': //Used to begin a new sql statement
    if (batchs.size() > 0) {
    v.addElement(getSQLStatements(batchs));
    batchs.removeAllElements();
    break;
    case 'S':
    case 's':
    case '?':
    if (batchs.size() > 0) {
    v.addElement(getSQLStatements(batchs));
    batchs.removeAllElements();
    v.addElement(temp);
    break;
    case '!': //Use it to get a large number of simple update statements
    if (batchs.size() > 0) {
    v.addElement(getSQLStatements(batchs));
    batchs.removeAllElements();
    String part1 = temp.substring(1);
    String part2 = br.readLine();
    for (int i = -2890; i < 1388; i += 39)
    batchs.addElement(part1 + i + part2);
    for (int i = 1890; i < 2388; i += 53) {
    batchs.addElement(part1 + i + part2);
    batchs.addElement(part1 + i + part2);
    for (int i = 4320; i > 4268; i--) {
    batchs.addElement(part1 + i + part2);
    batchs.addElement(part1 + i + part2);
    for (int i = 9389; i > 7388; i -= 83)
    batchs.addElement(part1 + i + part2);
    v.addElement(getSQLStatements(batchs));
    batchs.removeAllElements();
    break;
    default:
    batchs.addElement(temp);
    break;
    if (batchs.size() > 0) {
    v.addElement(getSQLStatements(batchs));
    batchs.removeAllElements();
    br.close();
    br = null;
    catch (java.io.FileNotFoundException fnfe) {
    v.addElement(sqlFile); //sqlFile is a sql command, not a file Name
    Object[] statements = new Object[v.size()];
    for (int i = 0; i < v.size(); i++)
    statements[i] = v.elementAt(i);
    return statements;
    public static void main(String argv[]) {
    try {
    String url;
    Object[] statements;
    switch (argv.length) {
    case 0: //Use it for the simplest test
    case 1:
    url = "jdbc:dbf:/.";
    if (argv.length == 0) {
    statements = new String[1];
    statements[0] = "select * from test";
    else
    statements = argv;
    break;
    case 2:
    url = argv[0];
    statements = getSQLStatements(argv[1]);
    break;
    default:
    throw new Exception(
    "Syntax Error: java testSQL url sqlfile");
    Class.forName("com.hxtt.sql.dbf.DBFDriver").newInstance();
    //Please see Connecting to the Database section of Chapter 2. Installation in Development Document
    Properties properties = new Properties();
    Connection con = DriverManager.getConnection(url, properties);
    Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_READ_ONLY);
    //Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
    // stmt.setMaxRows(0);
    stmt.setFetchSize(10);
    final boolean serializeFlag = false;//A test switch to serialize/deserialize the resultSet
    ResultSet rs;
    for (int i = 0; i < statements.length; i++) {
    if (statements[i] instanceof java.lang.String) {
    String temp = (java.lang.String) statements;
    switch (temp.charAt(0)) {
    case 'S':
    case 's':
    case '?':
    System.out.println(temp);
    rs = stmt.executeQuery(temp);
    if (serializeFlag) {
    // serialize the resultSet
    try {
    java.io.FileOutputStream fileOutputStream = new
    java.io.FileOutputStream("testrs.tmp");
    java.io.ObjectOutputStream
    objectOutputStream = new java.io.
    ObjectOutputStream(fileOutputStream);
    objectOutputStream.writeObject(rs);
    objectOutputStream.flush();
    objectOutputStream.close();
    fileOutputStream.close();
    catch (Exception e) {
    System.out.println(e);
    e.printStackTrace();
    System.exit(1);
    rs.close(); //Let the CONCUR_UPDATABLE resultSet release its open files at once.
    rs = null;
    // deserialize the resultSet
    try {
    java.io.FileInputStream fileInputStream = new
    java.io.FileInputStream("testrs.tmp");
    java.io.ObjectInputStream objectInputStream = new
    java.io.ObjectInputStream(
    fileInputStream);
    rs = (ResultSet) objectInputStream.
    readObject();
    objectInputStream.close();
    fileInputStream.close();
    catch (Exception e) {
    System.out.println(e);
    e.printStackTrace();
    System.exit(1);
    ResultSetMetaData resultSetMetaData = rs.
    getMetaData();
    int iNumCols = resultSetMetaData.getColumnCount();
    for (int j = 1; j <= iNumCols; j++) {
    // System.out.println(resultSetMetaData.getColumnName(j));
    /* System.out.println(resultSetMetaData.getColumnType(j));
    System.out.println(resultSetMetaData.getColumnDisplaySize(j));
    System.out.println(resultSetMetaData.getPrecision(j));
    System.out.println(resultSetMetaData.getScale(j));
    System.out.println(resultSetMetaData.
    getColumnLabel(j)
    + " " +
    resultSetMetaData.getColumnTypeName(j));
    Object colval;
    rs.beforeFirst();
    long ncount = 0;
    while (rs.next()) {
    // System.out.print(rs.rowDeleted()+" ");
    ncount++;
    for (int j = 1; j <= iNumCols; j++) {
    colval = rs.getObject(j);
    System.out.print(colval + " ");
    System.out.println();
    rs.close(); //Let the resultSet release its open tables at once.
    rs = null;
    System.out.println(
    "The total row number of resultset: " + ncount);
    System.out.println();
    break;
    default:
    int updateCount = stmt.executeUpdate(temp);
    System.out.println(temp + " : " + updateCount);
    System.out.println();
    else if (statements[i] instanceof java.lang.Object[]) {
    int[] updateCounts;
    Object[] temp = (java.lang.Object[]) statements[i];
    try {
    for (int j = 0; j < temp.length; j++){
    System.out.println( temp[j]);
    stmt.addBatch( (java.lang.String) temp[j]);
    updateCounts = stmt.executeBatch();
    for (int j = 0; j < temp.length; j++)
    System.out.println((j+1)+":"+temp[j]);
    for (int j = 0; j < updateCounts.length; j++)
    System.out.println((j+1)+":" +updateCounts[j]);
    catch (java.sql.BatchUpdateException e) {
    updateCounts = e.getUpdateCounts();
    for (int j = 0; j < updateCounts.length; j++)
    System.out.println((j+1)+":"+updateCounts[j]);
    java.sql.SQLException sqle = e;
    do {
    System.out.println(sqle.getMessage());
    System.out.println("Error Code:" +
    sqle.getErrorCode());
    System.out.println("SQL State:" + sqle.getSQLState());
    sqle.printStackTrace();
    while ( (sqle = sqle.getNextException()) != null);
    catch (java.sql.SQLException sqle) {
    do {
    System.out.println(sqle.getMessage());
    System.out.println("Error Code:" +
    sqle.getErrorCode());
    System.out.println("SQL State:" + sqle.getSQLState());
    sqle.printStackTrace();
    while ( (sqle = sqle.getNextException()) != null);
    stmt.clearBatch();
    System.out.println();
    stmt.close();
    con.close();
    catch (SQLException sqle) {
    do {
    System.out.println(sqle.getMessage());
    System.out.println("Error Code:" + sqle.getErrorCode());
    System.out.println("SQL State:" + sqle.getSQLState());
    sqle.printStackTrace();
    while ( (sqle = sqle.getNextException()) != null);
    catch (Exception e) {
    System.out.println(e.getMessage());
    e.printStackTrace();

  • Problem Obtaining multiple results from MySql Stored Proc via JDBC

    I've spent alot of time on this and I'd be really grateful for anyones help please!
    I have written a java class to execute a MySQL stored procedure that does an UPDATE and then a SELECT. I want to handle the resultset from the SELECT AND get a count of the number of rows updated by the UPDATE. Even though several rows get updated by the stored proc, getUpdateCount() returns zero.
    It's like following the UPDATE with a SELECT causes the updatecount info to be lost. I tried it in reverse: SELECT first and UPDATE last and it works properly. I can get the resultset and the updatecount.
    My Stored Procedure:
    delimiter $$ CREATE PROCEDURE multiRS( IN drugId int, IN drugPrice decimal(8,2) ) BEGIN UPDATE drugs SET DRUG_PRICE = drugPrice WHERE DRUG_ID > drugId; SELECT DRUG_ID, DRUG_NAME, DRUG_PRICE FROM Drugs where DRUG_ID > 7 ORDER BY DRUG_ID ASC; END $$
    In my program (below) callablestatement.execute() returns TRUE even though the first thing I do in my stored proc is an UPDATE not a SELECT. Is this at odds with the JDBC 2 API? Shouldn't it return false since the first "result" returned is NOT a resultset but an updatecount? Does JDBC return any resultsets first by default, even if INSERTS, UPDATES happened in the stored proc before the SELECTs??
    Excerpt of my Java Class:
    // Create CallableStatement CallableStatement cs = con.prepareCall("CALL multiRS(?,?)"); // Register input parameters ........ // Execute the Stored Proc boolean getResultSetNow = cs.execute(); int updateCount = -1; System.out.println("getResultSetNow: " +getResultSetNow); while (true) { if (getResultSetNow) { ResultSet rs = cs.getResultSet(); while (rs.next()) { // fully process result set before calling getMoreResults() again! System.out.println(rs.getInt("DRUG_ID") +", "+rs.getString("DRUG_NAME") +", "+rs.getBigDecimal("DRUG_PRICE")); } rs.close(); } else { updateCount = cs.getUpdateCount(); if (updateCount != -1) { // it's a valid update count System.out.println("Reporting an update count of " +updateCount); } } if ((!getResultSetNow) && (updateCount == -1)) break; // done with loop, finished all the returns getResultSetNow = cs.getMoreResults(); }
    The output of running the program at command line:
    getResultSetNow: true 28, Apple, 127.00 35, Orange, 127.00 36, Bananna, 127.00 37, Berry, 127.00 Reporting an update count of 0
    During my testing I have noticed:
    1. According to the Java documentation execute() returns true if the first result is a ResultSet object; false if the first result is an update count or there is no result. In my java class callablestatement.execute() will return TRUE if in the stored proc the UPDATE is done first and then the SELECT last or vica versa.
    2. My java class (above) is coded to loop through all results returned from the stored proc in succession. Running this class shows that any resultsets are returned first and then update counts last regardless of the order in which they appear in the stored proc. Maybe there is nothing unusual here, it may be that Java is designed to return any Resultsets first by default even if they didn't happen first in the stored procedure?
    3. In my stored procedure, if the UPDATE happens last then callablestatement.getUpdateCount() will return the correct number of updated rows.
    4. If the UPDATE is followed by a SELECT (see above) then callablestatement.getUpdateCount() will return ZERO even though rows were updated.
    5. I tested it with the stored proc doing SELECT - UPDATE - SELECT and again getUpdateCount() returns ZERO.
    6. I tested it with the stored proc doing SELECT - UPDATE - SELECT - UPDATE and this time getUpdateCount() returns the number rows updated by the last UPDATE and not the first.
    My Setup:
    Mac OS X 10.3.9
    Java 1.4.2
    mysql database 5.0.19
    mysql-connector 5.1.10 (connector/J)
    Maybe I have exposed a bug in JDBC?
    Thanks for your help.

    plica10 wrote:
    Jschell thank you for your response.
    I certainly don't mean to be rude but I often get taken that way. I like to state facts as I see them. I'd love to be proved wrong because then I would understand why my code doesn't work!
    Doesn't matter to me if you are rude or not. Rudeness actually makes it more entertaining for me so that is a plus. Nothing I have seen suggests rudeness.
    In response to your post:
    When a MySql stored procedure has multiple sql statements such as SELECT and UPDATE these statements each produce what the Java API documentation refers to as 'results'. A Java class can cycle through these 'results' using callableStatement dot getMoreResults(), getResultSet() and getUpdateCount() to retrieve the resultset object produced by Select queries and updateCount produced by Inserts, Deletes and Updates.
    As I read your question it seems to me that you have already proven that it does not in fact do that?
    You don't have to read this but in case you think I'm mistaken, there is more detail in the following website under the heading 'Using the Method execute':
    http://docsrv.sco.com/JDK_guide/jdbc/getstart/statement.doc.html#1000107
    Sounds reasonable. But does not your example code prove that this is not what happens for the database and driver that you are using?
    Myself I dont trust update counts at all since, in my experience some databases do not return them. And per other reports sometimes they don't return the correct value either.
    So there are two possibilities - your code is wrong or the driver/database does not do it. For me I would also question whether in the future the driver/database would continue to behave the same if you did find some special way to write your SQL so it does do it. And of course you would also need to insure that every proc that needed this would be written in this special way. Hopefully not too many of those.
    So this functionality is built into java but is not in common use amongst programmers. My java class did successfully execute a stored proc which Selected from and then finally Updated a table. My code displayed the contents of the Select query and told me how many rows were affected by the update.
    It isn't "built into java". It isn't built into jdbc either. If it works at all then the driver and by proxy the database are responsible for it. I suspect that you would be hard pressed to find anything in the JDBC spec that requires what that particular link claims. I believe it is difficult to find anything that suggests that update counts in any form are required.
    So you are left with hoping that a particular driver does do it.
    I suppose it is rare that you would want to do things this way. Returning rowcounts in OUT parameters would be easier but I want my code to be modular enough to cover the situation where a statement may return more than one ResultSet object, more than one update count, or a combination of ResultSet objects and update counts. The sql may need to be generated dynamically, its statements may be unknown at compile time. For instance a user might have a form that allows them to build their own queries...
    Any time I see statements like that it usually makes me a bit uncomfortable. If I am creating data layers I either use an existing framework or I generate the code. For the latter there is no generalization of the usage. Every single operation is laid out in its own code.
    And I have in fact created generalized frameworks in the past before. I won't do it again. Benefits of the other idioms during maintenance are too obvious.

  • Warning : PerformRecord.java use uncheck or unsafe operations

    /*When compile (with version 1.5.0_05) have a warnning message
    Note : PerformRecord.java use uncheck or unsafe operations
    Note : Recompile wiht -XLint : uncheck for details
    How can I solve this problem*/
    this is my code :
    import java.sql.*;
    import java.util.*;
    public class PerformRecord
         public static final String DEFAULT_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
    public static final String DEFAULT_URL = "Jdbc:Odbc:PersonalODBC";
    public static final String DEFAULT_USERNAME = "Personal";
    public static final String DEFAULT_PASSWORD = "moshan74";
         public Connection conn = null;
         public String querySQL;
         /*==Constructor class== */
         public PerformRecord()
              /*load JDBC driver*/
              try{
                   Class.forName(DEFAULT_DRIVER);
              }catch (ClassNotFoundException e){System.err.println(e.getMessage());}          
         /*===Method class*/
         /*set value for connection var*/
         public void getConnection()
              this.conn = setConnect();
         /*get QuerySQL*/
         public void setQuery(String sql)
              this.querySQL = sql;
         /*open connection */
         public Connection setConnect()
              try{
              conn = DriverManager.getConnection(DEFAULT_URL,DEFAULT_USERNAME,DEFAULT_PASSWORD);               
              }catch (SQLException e){System.err.print(e.getMessage());     }
              return conn;
         /*close connection*/
         public void closeConnect()
    try{
    conn.close();
    }catch (Exception e){ }
         /*execute query statement */
         public Object executeQuery()
              Object returnValue = null;
              try{
                   /*executing query and check result */
                   Statement stmt          = conn.createStatement();               
                   boolean hasResultSet = stmt.execute(querySQL);
                   if (hasResultSet)
                        /*get set of the record*/
                        ResultSet rs               = stmt.getResultSet();
                        /*get set of the column*/
                        ResultSetMetaData meta = rs.getMetaData();
                        /*amount column*/
                        int numColumns = meta.getColumnCount();
                        /*arrayLisst to add data*/     
                        List rows          = new ArrayList();
    while (rs.next())
    Map thisRow = new LinkedHashMap();// 1 element(1 row,i column)
    for (int i = 1; i <= numColumns; ++i)
    String columnName = meta.getColumnName(i);
    Object value = rs.getObject(columnName);
    thisRow.put(columnName, value);
    rows.add(thisRow);
    rs.close();
    stmt.close();
                   this.closeConnect();
    returnValue = rows;
    else
    int updateCount = stmt.getUpdateCount();
    returnValue = new Integer(updateCount);
              }catch (SQLException e){System.err.print(e.getMessage());     }
    return returnValue;
    ps>> I want to to use Generics to help it but I don't know how to do it in the right way . Can you you help me?
    Thanks
    Arunya

    regarding your Map/LinkedHashMap, since you keys are String and you values are Objects... you would define you Map using those two as you data type pair...
    ap<String,Object>thisRow = new LinkedHashMap<String,Object>();and similar for you List/ArrayList where you putting Maps into...
    List<Map<String,Object>> rows = new ArrayList<Map<String,Object>>();for more information on generics read...
    [url http://java.sun.com/docs/books/tutorial/java/javaOO/generics.html]Sun's The Java Tutorial : Generics
    - MaxxDmg...
    - ' He who never sleeps... '

  • BUG: implied .executeBatch() failing with new drivers?

    Our application uses batching with SQLJ and is experiencing an issue with the latest driver versions and Java 1.5. It used to work fine when issuing a few INSERT statements with a specified execution context and then letting the SQLJ COMMIT execute the pending statements in the batch when the transaction was finished. With the new drivers, the SQLJ COMMIT is successful but it doesn't write any of the pending batches to database as it is supposed to (per the Oracle Database SQLJ Developer's Guide and Reference).
    In a small testcase I prepared (see the next message for the code), it shows a new batch was created for the first statement (NEW_BATCH_COUNT returned). It also shows subsequent statements are added to the existing batch (ADD_BATCH_COUNT returned). The COUNT() statements show the data never makes it to the database and the table contents were verified in the database after program completion.
    Java: 1.5.0_10
    Oracle Database: Oracle9i Enterprise Edition Release 9.2.0.1.0 - 64bit Production
    Oracle JDBC Driver: 10.2.0.2.0
    translator.jar: JPublisher 10g Release 10.2
    runtime12.jar: JPublisher 10g Release 10.2
    Can anyone please confirm this is a bug?
    Thanks much

    //---------- C O D E ---------------------------------
    package com.sqljtest;
    import java.sql.*;
    import java.util.*;
    import sqlj.runtime.ref.*;
    import sqlj.runtime.*;
    import oracle.sqlj.runtime.*;
    public class Sqljtest extends java.lang.Object {
    public static void main(String[] args) {
    Connection con = null;
    DefaultContext connContext = null;
    ExecutionContext ec = null;
    try {
    String driver = "oracle.jdbc.OracleDriver";
    String url = "jdbc:oracle:thin:@127.0.0.1:1521:mysid";
    String user = "scott";
    String password = "tiger";
    DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
    con = DriverManager.getConnection(url, user, password);
    con.setAutoCommit(false);
    connContext = Oracle.getConnection(con);
    connContext.getConnection().setAutoCommit(false);
    ec = new ExecutionContext();
    ec.setBatching(true);
    Vector collection = new Vector();
    collection.add("one");
    collection.add("two");
    collection.add("three");
    collection.add("four");
    collection.add("five");
    int rowCount, updateCount;
    #sql [connContext] { SELECT COUNT(1) INTO :rowCount FROM sqljtest };
    System.out.println("before rowCount:" + rowCount);
    for (int i = 0; i < collection.size(); i++) {
    #sql [connContext, ec] {
    INSERT INTO sqljtest blah VALUES (: ((String)collection.get(i)) )
    updateCount = ec.getUpdateCount();
    System.out.println("INSERT (" collection.get(i) "): " + updateCount);
    #sql [connContext] { SELECT COUNT(1) INTO :rowCount FROM sqljtest };
    System.out.println("after inserts rowCount:" + rowCount);
    #sql [connContext] {COMMIT};
    #sql [connContext] { SELECT COUNT(1) INTO :rowCount FROM sqljtest };
    System.out.println("after sqlj commit rowCount:" + rowCount);
    } catch (Exception e) {
    System.err.println("Exception e: " + e.toString());
    } finally {
    try {
    if (connContext != null && !connContext.isClosed()) {
    connContext.close(ConnectionContext.CLOSE_CONNECTION);// .CLOSE_CONNECTION
    if (con != null) {
    con.close();
    } catch (Exception e) {
    System.err.println("Exception while closing connections: " + e.toString());
    //---------- O U T P U T -----------------------------
    run SQLJ Test:
    [SQLJ Test] before rowCount:0
    [SQLJ Test] INSERT (one): -3
    [SQLJ Test] INSERT (two): -4
    [SQLJ Test] INSERT (three): -4
    [SQLJ Test] INSERT (four): -4
    [SQLJ Test] INSERT (five): -4
    [SQLJ Test] after inserts rowCount:0
    [SQLJ Test] after sqlj commit rowCount:0

  • Problem with Batch Updates

    Hi All,
    I have a requirement where in I have to use batch updates. But if there's a problem in one of the updates, I want the rest of the updates to ingore this and continue with the next statement in the batch. Is this not one of the features in BatchUpdates in JDBC2? I have been trying to accomplish this since 2 days now. Can anyone help me with this. Can anyone please help me with this?
    FYI, I have tried the following.
    I have 3 test updates in my batch.
    2 nd statement is an erraneous statement(deliberate). Other 2 statements are fine. It is appropriatley throwing 'BatchUpdateException'. when I ckeck the "arrays of ints" reurned by executeBatch() as well as BatchUpdateException.getUpdateCounts() are returning an arrays of size '0'. If remeove the erraneous statement, behaviour is as expected.
    Thanks in advance,
    Bharani

    The next paragraph of the same API doc:
    If the driver continues processing after a failure, the array returned by the method BatchUpdateException.getUpdateCounts will contain as many elements as there are commands in the batch, and at least one of the elements will be the following:
    3. A value of -3 -- indicates that the command failed to execute successfully and occurs only if a driver continues to process commands after a command fails
    A driver is not required to implement this method.

  • SQL statements:help

    here is a sample code of my application....
    int initialDelay = 10000; // start after 10 second
    int period = 10000*60*60*24*30; // repeat every month
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
    public void run() {
    try {
    MyDBConnection jdbc = new MyDBConnection();
    jdbc.init();
    Connection conn = jdbc.getMyConnection();
    Statement stmt = conn.createStatement();
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date date = new Date();
    String[] tbl = {"emticket","emattachment","emhistory","emtracker"};
    progTxt.setText("");
    Logs l = new Logs();
    l.append("Auto Archive");
    date.getTime();
    //Archive data
    progTxt.append("\n\n");
    progTxt.append(" Archiving Data...\n ");
    stmt.execute("select * into outfile 'c:/emticket " + dateFormat.format(date) + ".csv' fields terminated by ',' enclosed by '\"' lines terminated by '\\n' from emticket where RcvDateTime between date_sub(curdate(),interval 90 day) and curdate()");
    stmt.execute("select * into outfile 'c:/emattachment " + dateFormat.format(date) + ".csv' fields terminated by ',' enclosed by '\"' lines terminated by '\\n' from emattachment where EmID in (select EmID from emticket where RcvDateTime between date_sub(curdate(),interval 90 day) and curdate())");
    stmt.execute("select * into outfile 'c:/emhistory " + dateFormat.format(date) + ".csv' fields terminated by ',' enclosed by '\"' lines terminated by '\\n' from emhistory where TicketID in (select TicketID from emticket where RcvDateTime between date_sub(curdate(),interval 90 day) and curdate())");
    stmt.execute("select * into outfile 'c:/emtracker " + dateFormat.format(date) + ".csv' fields terminated by ',' enclosed by '\"' lines terminated by '\\n' from emtracker where TicketID in (select TicketID from emticket where RcvDateTime between date_sub(curdate(),interval 90 day) and curdate())");
    progTxt.append("Done.\n\n");
    //Delete data
    progTxt.append(" Deleting Data... ");
    stmt.execute("delete emticket, emattachment, emhistory, emtracker from emticket, emattachment, emhistory, emtracker where emattachment.EmID=emticket.EmID and emhistory.TicketID=emticket.TicketID and emtracker.TicketID=emtracker.TicketID and where RcvDateTime
    "_______"DATE_SUB(CURDATE(),INTERVAL 90 DAY) and CURDATE())");
    System.out.println(stmt.getUpdateCount());
    progTxt.append("Done.\n\n");
    Here's what i want to do....I want to backup file for the current date back to 3 mos...e.g 2007-05-23 down to 2007-02-23...then delete the remaining records...before"02-23-2007 to 05-23-2007"....this is where the query part i that doesn't work....
    Delete data
    progTxt.append(" Deleting Data... ");
    stmt.execute("delete emticket, emattachment, emhistory, emtracker from emticket, emattachment, emhistory, emtracker where emattachment.EmID=emticket.EmID and emhistory.TicketID=emticket.TicketID and emtracker.TicketID=emtracker.TicketID and where RcvDateTime
    "_______"DATE_SUB(CURDATE(),INTERVAL 90 DAY) and CURDATE())");
    System.out.println(stmt.getUpdateCount());
    progTxt.append("Done.\n\n")
    I tried putting <>=which means not equal in the "_____"but it fails to work..can somebody help me to work out with this query.

    I don't know MySQL, but shouldn't you just use <= ? I also don't understand what the final part 'and CURDATE()' is for...

Maybe you are looking for

  • Messages won't go away. Help me!

    So I have these 7 messages, all the same, sent at received at the same time, in my Inbox. they are Junk from: Mail Delivery System" and the subject reads:"Undelivered mail returned to sender" I delete them, check ANY other mailbox, and when I return

  • HT4009 how can i cancel a subscription for an app that auto-renews

    i am away from the device that the app is downloaded to.  i will likely forget to go into settings and process the cnacellation.  is there a way to cancel online?  i do not have iTunes at work.  thanks, ~sg

  • Loss of sound on websites...

    I have lost the playback sound on the websites I've using...although I do get output sound from iTunes....I recently installed the iSRS demo player which seemed to crash iTunes..? and also I've been using Audicity to copy music from a MiniDisk to my

  • HT201441 What if I can't find or contact my previous owner?

    I have bought a iPhone from a second hand store when I tried to set up the iPhone it says that the iPhone is linked with a apple account, but the probelm is that I don't know the previous user of that phone so what do I do?

  • TS3694 whats with error 1015 ????

    i reset my iphone then it crashed then i had to do a hard reset to get it to the connect to itunes phease on my iphone and i tried hookin it upto itunes and it starts sortin it out fine then it comes up wit unknown error 1015 how do i sort it out hel