ArrayList to ResultSet

Hi All,
I am in unique problem which google could not give me a solution. I hope somebody here has do some stuff like this.
I have a DEPARTMENT Table:
CREATE TABLE DEPARTMENT
(dept_id int,
dept_name varchar(50),
ext_code varchar(10) )
I have a POJO class "Department" which represents DEPARTMENT table:
public class Department implements Serializable {
private Integer departmentId;
private String departmentName;
private String externalCode;
public Integer getDepartmentId() {
     return departmentId;
private void setDepartmentId(Integer departmentId) {
     this.departmentId = departmentId;
public String getDepartmentName() {
     return departmentName;
public void setDepartmentName(String departmentName) {
     this.departmentName = departmentName;
public String getExternalCode() {
     return externalCode;
public void setExternalCode(String externalCode) {
     this.externalCode = externalCode;
Now I am communicating with 2 different programs. First program is sending me Departments as an ArrayList.
List departmentsList = new ArrayList();
departmentsList = aDepartmentDAO.getAllDepartments();
The second program requires those Departments in a ResultSet format.
I have to write code to translate an ArrayList to a ResultSet.
Is it doable? Please explain the steps involved.
Thanks
Uryl

To give you some idea of what you may have to do...
You need to fill in these methods to create your own ResultSet
Most of these you can leave blank as long as you can determine which methods are actually used.
I woudl create an Iterator from the ArrayList which would allow you to set through the values in the same way a ResultSet steps through the rows.
I would expect you can leave the update* methdos blank.
public class MyResultSet implements ResultSet {
    private final List list;
    public MyResultSet(List list) {
        this.list = list;
    public boolean absolute(int row) throws SQLException {
        return false;
    public void afterLast() throws SQLException {
    public void beforeFirst() throws SQLException {
    public void cancelRowUpdates() throws SQLException {
    public void clearWarnings() throws SQLException {
    public void close() throws SQLException {
    public void deleteRow() throws SQLException {
    public int findColumn(String columnName) throws SQLException {
        return 0;
    public boolean first() throws SQLException {
        return false;
    public Array getArray(String colName) throws SQLException {
        return null;
    public Array getArray(int i) throws SQLException {
        return null;
    public InputStream getAsciiStream(int columnIndex) throws SQLException {
        return null;
    public InputStream getAsciiStream(String columnName) throws SQLException {
        return null;
    public BigDecimal getBigDecimal(int columnIndex) throws SQLException {
        return null;
    @Deprecated public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException {
        return null;
    public BigDecimal getBigDecimal(String columnName) throws SQLException {
        return null;
    @Deprecated public BigDecimal getBigDecimal(String columnName, int scale) throws SQLException {
        return null;
    public InputStream getBinaryStream(int columnIndex) throws SQLException {
        return null;
    public InputStream getBinaryStream(String columnName) throws SQLException {
        return null;
    public Blob getBlob(String colName) throws SQLException {
        return null;
    public Blob getBlob(int i) throws SQLException {
        return null;
    public boolean getBoolean(int columnIndex) throws SQLException {
        return false;
    public boolean getBoolean(String columnName) throws SQLException {
        return false;
    public byte getByte(int columnIndex) throws SQLException {
        return 0;
    public byte getByte(String columnName) throws SQLException {
        return 0;
    public byte[] getBytes(int columnIndex) throws SQLException {
        return new byte[0];
    public byte[] getBytes(String columnName) throws SQLException {
        return new byte[0];
    public Reader getCharacterStream(int columnIndex) throws SQLException {
        return null;
    public Reader getCharacterStream(String columnName) throws SQLException {
        return null;
    public Clob getClob(String colName) throws SQLException {
        return null;
    public Clob getClob(int i) throws SQLException {
        return null;
    public int getConcurrency() throws SQLException {
        return 0;
    public String getCursorName() throws SQLException {
        return null;
    public Date getDate(int columnIndex) throws SQLException {
        return null;
    public Date getDate(int columnIndex, Calendar cal) throws SQLException {
        return null;
    public Date getDate(String columnName) throws SQLException {
        return null;
    public Date getDate(String columnName, Calendar cal) throws SQLException {
        return null;
    public double getDouble(int columnIndex) throws SQLException {
        return 0;
    public double getDouble(String columnName) throws SQLException {
        return 0;
    public int getFetchDirection() throws SQLException {
        return 0;
    public int getFetchSize() throws SQLException {
        return 0;
    public float getFloat(int columnIndex) throws SQLException {
        return 0;
    public float getFloat(String columnName) throws SQLException {
        return 0;
    public int getInt(int columnIndex) throws SQLException {
        return 0;
    public int getInt(String columnName) throws SQLException {
        return 0;
    public long getLong(int columnIndex) throws SQLException {
        return 0;
    public long getLong(String columnName) throws SQLException {
        return 0;
    public ResultSetMetaData getMetaData() throws SQLException {
        return null;
    public Object getObject(String colName, Map<String, Class<?>> map) throws SQLException {
        return null;
    public Object getObject(int columnIndex) throws SQLException {
        return null;
    public Object getObject(String columnName) throws SQLException {
        return null;
    public Object getObject(int i, Map<String, Class<?>> map) throws SQLException {
        return null;
    public Ref getRef(String colName) throws SQLException {
        return null;
    public Ref getRef(int i) throws SQLException {
        return null;
    public int getRow() throws SQLException {
        return 0;
    public short getShort(int columnIndex) throws SQLException {
        return 0;
    public short getShort(String columnName) throws SQLException {
        return 0;
    public Statement getStatement() throws SQLException {
        return null;
    public String getString(int columnIndex) throws SQLException {
        return null;
    public String getString(String columnName) throws SQLException {
        return null;
    public Time getTime(int columnIndex) throws SQLException {
        return null;
    public Time getTime(int columnIndex, Calendar cal) throws SQLException {
        return null;
    public Time getTime(String columnName) throws SQLException {
        return null;
    public Time getTime(String columnName, Calendar cal) throws SQLException {
        return null;
    public Timestamp getTimestamp(int columnIndex) throws SQLException {
        return null;
    public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException {
        return null;
    public Timestamp getTimestamp(String columnName) throws SQLException {
        return null;
    public Timestamp getTimestamp(String columnName, Calendar cal) throws SQLException {
        return null;
    public int getType() throws SQLException {
        return 0;
    @Deprecated public InputStream getUnicodeStream(int columnIndex) throws SQLException {
        return null;
    @Deprecated public InputStream getUnicodeStream(String columnName) throws SQLException {
        return null;
    public URL getURL(int columnIndex) throws SQLException {
        return null;
    public URL getURL(String columnName) throws SQLException {
        return null;
    public SQLWarning getWarnings() throws SQLException {
        return null;
    public void insertRow() throws SQLException {
    public boolean isAfterLast() throws SQLException {
        return false;
    public boolean isBeforeFirst() throws SQLException {
        return false;
    public boolean isFirst() throws SQLException {
        return false;
    public boolean isLast() throws SQLException {
        return false;
    public boolean last() throws SQLException {
        return false;
    public void moveToCurrentRow() throws SQLException {
    public void moveToInsertRow() throws SQLException {
    public boolean next() throws SQLException {
        return false;
    public boolean previous() throws SQLException {
        return false;
    public void refreshRow() throws SQLException {
    public boolean relative(int rows) throws SQLException {
        return false;
    public boolean rowDeleted() throws SQLException {
        return false;
    public boolean rowInserted() throws SQLException {
        return false;
    public boolean rowUpdated() throws SQLException {
        return false;
    public void setFetchDirection(int direction) throws SQLException {
    public void setFetchSize(int rows) throws SQLException {
    public void updateArray(int columnIndex, Array x) throws SQLException {
    public void updateArray(String columnName, Array x) throws SQLException {
    public void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException {
    public void updateAsciiStream(String columnName, InputStream x, int length) throws SQLException {
    public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException {
    public void updateBigDecimal(String columnName, BigDecimal x) throws SQLException {
    public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException {
    public void updateBinaryStream(String columnName, InputStream x, int length) throws SQLException {
    public void updateBlob(int columnIndex, Blob x) throws SQLException {
    public void updateBlob(String columnName, Blob x) throws SQLException {
    public void updateBoolean(int columnIndex, boolean x) throws SQLException {
    public void updateBoolean(String columnName, boolean x) throws SQLException {
    public void updateByte(int columnIndex, byte x) throws SQLException {
    public void updateByte(String columnName, byte x) throws SQLException {
    public void updateBytes(int columnIndex, byte x[]) throws SQLException {
    public void updateBytes(String columnName, byte x[]) throws SQLException {
    public void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException {
    public void updateCharacterStream(String columnName, Reader reader, int length) throws SQLException {
    public void updateClob(int columnIndex, Clob x) throws SQLException {
    public void updateClob(String columnName, Clob x) throws SQLException {
    public void updateDate(int columnIndex, Date x) throws SQLException {
    public void updateDate(String columnName, Date x) throws SQLException {
    public void updateDouble(int columnIndex, double x) throws SQLException {
    public void updateDouble(String columnName, double x) throws SQLException {
    public void updateFloat(int columnIndex, float x) throws SQLException {
    public void updateFloat(String columnName, float x) throws SQLException {
    public void updateInt(int columnIndex, int x) throws SQLException {
    public void updateInt(String columnName, int x) throws SQLException {
    public void updateLong(int columnIndex, long x) throws SQLException {
    public void updateLong(String columnName, long x) throws SQLException {
    public void updateNull(int columnIndex) throws SQLException {
    public void updateNull(String columnName) throws SQLException {
    public void updateObject(int columnIndex, Object x) throws SQLException {
    public void updateObject(int columnIndex, Object x, int scale) throws SQLException {
    public void updateObject(String columnName, Object x) throws SQLException {
    public void updateObject(String columnName, Object x, int scale) throws SQLException {
    public void updateRef(int columnIndex, Ref x) throws SQLException {
    public void updateRef(String columnName, Ref x) throws SQLException {
    public void updateRow() throws SQLException {
    public void updateShort(int columnIndex, short x) throws SQLException {
    public void updateShort(String columnName, short x) throws SQLException {
    public void updateString(int columnIndex, String x) throws SQLException {
    public void updateString(String columnName, String x) throws SQLException {
    public void updateTime(int columnIndex, Time x) throws SQLException {
    public void updateTime(String columnName, Time x) throws SQLException {
    public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException {
    public void updateTimestamp(String columnName, Timestamp x) throws SQLException {
    public boolean wasNull() throws SQLException {
        return false;
}

Similar Messages

  • How to move (ArrayList || Statement || ResultSet) information  - dataSet

    I'm building a MySQL based DB application. Using jdbc connector from mysql.
    I now have SQL query results in Statement object, in ResultSet and in ArrayList. Is there any posibility to pass any information from any of theees to dataSet object.
    because i'm using jdbTable, and this thing doesn't work without dataSet... ...doh
    many thanks
    simas

    Hello,
    Check out the Performing Inserts, Updates, and Deletes tutorial
    http://developers.sun.com/prodtech/javatools/jscreator/learning/tutorials/index.jsp
    Also, you can search the forum. There have been some
    discussions on MySQL
    John
    JSC QA

  • Conversion of ArrayList to Resultset Back...

    hey,
    Is there anyway i can create ResultSet From ArrayList ..where my Hibernate will returns me the arraylist ..i just want to convert that one to ResultSet for japserreports..is there anyway plz help me?

    Sure there's a way. ResultSet is an interface so you are free to write an implementation of it that has an ArrayList as its backing data. But there are over 100 methods to implement so I would be inclined to look harder for some other solution.

  • Help :add multiple rows from Resultset to ArrayList ?

    My query returns one column and multiple rows. In Java code , I am trying to get this data in array or arraylist through ResultSet
    ex:
    item_num
    p001
    p002
    p003
    when I print, it only gets the item in the first row.
    ArrayList myArrayList = new ArrayList();
    resultset = preparedstatement.executeQuery();
    if (resultset.next())
    myArrayList.add(new String(resultset.getString("item_num")));
    Print:
    for (int j = 0 ; j < myArrayList.size() ; j++ )
    System.out.println((String)myArrayList.get(j)); --this prints only the first item.
    can someone assist ?

    changing if to while fixed it.

  • How to create an array with a resultset

    Hello,
    Can somebody suggest a good way to put the result set of a query of a standard table into an array?
    The result set will have 0 to many rows. I can copy the rows into the array one row at a time, but I don't know what size array to create at the start.
    Any suggestions are greatly appreciated.
    Thank you,
    Logan

    ***The Following code will return u the ArrayList Object From ur resultset******
    public static ArrayList resultSetToArrayList(ResultSet rs){
              ArrayList results = null;
              try{
                        ResultSetMetaData md = rs.getMetaData();
                        int columns = md.getColumnCount();
                        results = new ArrayList();
                        while (rs.next()){
                             HashMap row = new HashMap();
                             results.add(row);
                             for(int i=1; i<=columns; i++){
                                  row.put(md.getColumnName(i),rs.getObject(i));
              catch(Exception e)
                   e.printStackTrace();
    return results;
    }

  • Re-using statements with open ResultSet

    Hi,
    Question about re-using connections while keeping a result set open - basically I am trying to do:
    Connection conn = dataSource.getConnection();
    Statement stmt = conn.createStatement();
    if (stmt.execute(QUERY))
    resultSet = stmt.getResultSet();
    ArrayList userList = new ArrayList();
    while (resultSet.next())
    String str = resultSet.getString(1));
    String otherStr = getString(str, conn));
    where getString(str,conn) performs another query.
    Is it recommended to use another connection for the call to the getString() method or is it safe to use the same connection? There won't be any other threads using the connection btw.
    Thanks,
    Johan

    Unfortunately it isn't - i want to look up a list of
    users (the first lookup) and then for each user, I
    want to find out what groups they belong to. So the
    sub-query is needed ... :(
    I could do it in one query, but then I would have to
    do a (sort of ugly) loop in the resultset while loop
    ...Are you a former VB programmer? Just curious...
    I'll bet you'd be FAR better off doing a JOIN to bring back that data. If you have X users, you're saying that you're going to run a query like this once:
    SELECT USER_ID FROM USERS WHERE SOME_ATTRIBUTE = y;Then you're going to loop over all the USER_IDs you get back and run another query like this, once per user:
    SELECT GROUP_ID FROM GROUPS WHERE USER_ID = this_user_idwhere this_user_id is the current USER_ID value in your loop.
    That means you're going to have X+1 network roundtrips. Network calls are the slowest thing you can possibly do.
    Instead of doing that, someone who really knew SQL would write this:
    SELECT GROUP_ID
    FROM GROUPS, USERS
    WHERE
    GROUPS.USER_ID = this_user_id AND
    GROUPS.USER_ID = USERS.USER_IDThat'll mean ONE network roundtrip - MUCH faster. It's called a JOIN, in case you didn't know.
    The loop over the ResultSet will be no uglier than what you'll do to accomplish the JOIN in your own code. I'll bet it's cleaner. AND it'll do it in 1/(X+1) the time, because you'll only do 1 network roundtrip instead of (X+1).
    Doing the JOIN in your code is the most foolish thing you can possibly do. You're saying that you can optimize the query better than the guy who wrote the SQL engine and optimizer for your database. I highly doubt it. JMO - MOD

  • Checking if resultset still active?

    I want to return a ResultSet which basically handles some query i.e.
    public ResultSet doSomething(int chr, int startPos, int endPos, int strainsThreshold, float minGeneDensity) throws SQLException {
                    String someQuery = "";          
              // this should force incremental streaming of a large result set
              if(conn != null){
              stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
                       java.sql.ResultSet.CONCUR_READ_ONLY);
              stmt.setFetchSize(Integer.MIN_VALUE);
              return stmt.executeQuery(someQuery);
              }else
              return null;
         }This is running in a web application. However, if I stop a query running halfway through e.g. by pressing the stop button on the browser and then re-run the query the current resultSet is still active and throws an exception. Checking the API states that when the statement is fully executed the resultSet will be closed automatically but in this case it isn't. Is there any way of checking whether the resultSet is active or a way of closing it if a query ends prematurely?

    I suspect you need to change your function so it is tread safe. That way, a second sql request can be made even if the first one is pending. In your function, do the following (note all variables except dataSource are local variables so its thread safe): Note you can't return the resultSet because its closed within the function before the function is returned. Instead, copy the data from the resultSet into some type of array. (resultSet.getString("firstName") ) and return the array.
    public ArrayList myFunction(){
    Connection conn=null;
    PreparedStatement pstmt1= null;
    ResultSet resultSet=null
    ArrayList list1=new ArrayList();
    try{
    conn= dataSource.getConnection();
    pstmt1= conn.prepareStatement();
    resultSet= pstmt1.executeQuery();
    while(resultSet.next()){
    arrayList.add(resultSet.getString("lastName");
    return arrayList;
    } catch (SqlException e){
    } finally {
    if(rsultSet!=null)
    resultSet.close();
    if(pstmt1!=null)
    pstmt1.close();
    if(conn!=null)
    conn.close();
    Next, on your JSP page block you submit button from being clicked more than once until the page is re-rendered with the response from the server.
    If your query takes a long time to run and the user would consider trying to kill it, you cant. The database will execute the query to completion. I suggest instead limiting the amount of data fetched so its doesnt take so long. Add a filter to the page. Example: a textfield to filter by last Name. Enter 'B' in the textfield, and programmatically change the sql to 'select * from person where lastName like 'B%'.

  • ResultSet.next() throws NullPointerException

    Hello,
    When running the following code:
    import java.sql.*;
    class DatabaseDriver {
         private int                    databaseType;
         private String               error;
         private Connection     con;
         private Statement          statement;
         private ResultSet          rs;
         static final int          MYSQL_DB_TYPE = 1;
         static final int          PGSQL_DB_TYPE = 2;
         static final int          MSSQL_DB_TYPE = 3;
         static final int          ORACLE_DB_TYPE = 4;
         public DatabaseDriver (int dbType) {
              databaseType = dbType;
              try {
                   switch (dbType) {
                        case MYSQL_DB_TYPE:
                             Class.forName("com.mysql.jdbc.Driver").newInstance();
                             break;
                        case PGSQL_DB_TYPE:
                             Class.forName("org.postgresql.Driver").newInstance();
                             break;
                        case MSSQL_DB_TYPE:
                             Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
                             break;
                        case ORACLE_DB_TYPE:
                             Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
                             break;
              } catch (Exception e) {
                   error = "could not load driver";
         public boolean connect (String server, String user, String password) {
              try {
                   con = DriverManager.getConnection("jdbc:mysql://" + server + "?user=" + user + "&password=" + password);
              } catch (Exception e) {
                   error = "could not connect to the database";
                   return false;
              return true;
         public boolean execQuery (String query) {
              try {
                   statement = con.createStatement();
                   if (statement.execute(query)) {
                        rs = statement.getResultSet();
                   while (rs.next()) {
                        System.out.println(rs.getString("1") + "\t" + rs.getString("2"));
                   rs.close();
                   rs = null;
                   statement.close();
                   statement = null;
              } catch (Exception e) {
                   error = e.toString();
                   e.printStackTrace();
                   return false;
              return true;
         public String getError () {
              return error;
         public boolean disconnect () {
              return true;
    class Test {
         public static void main (String[] args) {
              DatabaseDriver db = new DatabaseDriver(1);
              db.connect(args[0],args[1],args[2]);
              db.execQuery("USE " + args[3] + ";");
              db.execQuery("SELECT * FROM te;");
              System.out.println(db.getError());
    }I receive this in the printout:
    java.lang.NullPointerException
         at DatabaseDriver.execQuery(DatabaseDriver.java:61)
         at Test.main(Test.java:7)
    bla1     bla2
    bla6     bla7
    java.lang.NullPointerException
    Line 61
    while (rs.next()) {
    I have read a lot of other posts that say that the connection object is null or the recordset is empty, but it seems that neither of those are the case considering I am able to printout the two rows properly.
    Can someone please explain to me what I am doing wrong and how to fix it?
    Thanks

    You can pepper your code with System.out.println() statements to determine what value goes into the execute() statement before it runs.
    In the following, I think the first statement will probably return false. What is this sql trying to accomplish that you think it sould return true? Even if it returned true, what value do you expect in the resultSet?
    db.execQuery("USE " + args[3] + ";");
    db.execQuery("SELECT * FROM te;");
    As a side note, I strongly suggest you use connection pooling and not driverManager. here is an example of getting and returning a connection properly (all within a function)
    public String[] myFunction(){
    Connection conn=null;
    PreparedStatement pstmt1= null;
    ResultSet resultSet=null;
    ArrayList list1; //array that can grow in size
    try{
    list1=new ArrayList();
    conn= dataSource.getConnection();
    pstmt1= conn.prepareStatement();
    resultSet= pstmt1.executeUpdate();
    while(resultSet.next()){
    arrayList.add(resultSet.getString("lastName");
    return ( String[] ) arrayList.toArray( new String[arrayList.size()] );
    } catch (SqlException e){
    e.printStackTrace();
    } finally {
    if(rsultSet!=null)
    resultSet.close();
    if(pstmt1!=null)
    pstmt1.close();
    if(conn!=null)
    conn.close();
    }

  • Any suggestions for my code.

    Hi,
    I wrote this little piece of code to reduce some of the work I need to do when doing database access. I intend to use if with mySQL and mostly web based applications. It'll probably use it quite a bit, and since it's my first try at writing something like this I figured I'd post the code to see if anyone can find any problems. I've already tested it and it works, so I'm mostly interested in any feedback about performance issues.
    I'd really like to know if there's any way I can get the number of rows in a result set before I start going through it. That way I could return the data in an Object[][] array (I'd assume it'd be a little faster to add values to than the ArrayList).
    Here's the code...
    * SQLGruntBean.java
    * Created on November 22, 2002, 12:37 PM
    package com.vacode.beans.sql;
    import java.sql.*;
    import java.util.*;
    /** This bean is a generic class that can be used to access any type of SQL
    *  database.  To use it with an application that accesses an SQL database
    *  do the following:
    *  <p>1. Create a new instance of SQLGruntBean.</p>
    *  <p>2. Set the SQL connection source by calling setConnection(Connection).</p>
    *  <p>3. Set the SQL query you wish to perform by calling setSqlQuery(String).
    *  <br><b>Note:</b> You may replace all values with question mark place holders
    *  as long as you also perform step 4.</p>
    *  <p>4. (OPTIONAL) Set the values that are represented by question mark place
    *  holders by calling setSqlValues.  This method requires an Object array as
    *  input.</p>
    *  <p>5. (OPTIONAL) Set the maximum number of results to be retrieved by calling
    *  setMaxRows.  If left unset it will default to 100.  This method should not
    *  be used as a replacement for the LIMIT parameter in an SQL query.  It is
    *  merely a backup in case an excessive number of results are returned
    *  erroneously.</p>
    *  <p>6. Once all the necessary variables are set you may call either
    *  executeQuery or executeUpdate to perform the intended task.</p>
    *  <p>     <b><i><u>EXAMPLE</u></i></b></p>
    *  <p>
    *  <code>
    *  <br>SQLGruntBean sgb = new SQLGruntBean();
    *  <br>Object[] values = new Object[1];
    *  <br>ArrayList data = null;
    *  <br><br>
    *  <br>sgb.setConnection(dataSource.getConnection);
    *  <br>sgb.setSqlQuery("SELECT * FROM USERS WHERE firstName = ?");
    *  <br>values[0] = "John";
    *  <br>sgb.setSqlValues(values);
    *  <br>data = sgb.executeQuery();
    *  </code>
    *  </p>
    *  <p>The necessary try / catch blocks and error handling have been left out of
    *  this example, but will need to be implemented for production code.</p>
    * @author  Vacode Web Systems
    * @version 1.0
    public class SQLGruntBean
        // Define global variables
        private Connection dbConnection = null;
        private String sqlQuery = null;
        private int maxRows = 100;  // Default to 100 in case it is not set
        private Object[] sqlValues = null;
        // End global variables
        /** A write only method for defining the connection to an SQL
         *  database
        public void setConnection(Connection sqlConnectionObject)
         this.dbConnection = sqlConnectionObject;
        /** A write only method for defining the SQL query that is to be
         *  executed.*/
        public void setSqlQuery(String sqlQuery)
         this.sqlQuery = sqlQuery;
        /** Defines the maximum number of rows that are to be retrieved from the
         *  result set.  This is more of a back up than anything as the sql query
         *  should contain a limit parameter if the query is going to return an
         *  excessive number of results. */
        public void setMaxRows(int maximumRows)
         this.maxRows = maximumRows;
        /** A write only method for defining the dynamic values that are
         *  to replace the question mark placeholders in the sql query.*/
        public void setSqlValues(Object[] values)
         this.sqlValues = values;
        /** Used to execute an sql query.  The executed query is defined by calling
         *  setSqlQuery prior to this method.  The database connection to be used
         *  is defined by calling setConnection prior to this method. */
        public ArrayList executeQuery() throws SQLException
         // Define the local variables that will be used within this method
         ArrayList data = null;
         // End local variables
         if(this.sqlValues!=null && this.sqlValues.length>0)
             /* A prepared statement needs to be executed because the
              * sqlQuery is going to contain ? placeholders rather than
              * actual values.  It is necessary to replace these place
              * holders with their corresponding values.*/
             data = executePreparedQuery();
         else
             // A regular sql query needs to be executed.
             data = executeRegularQuery();
         return(data);
        /** Used to execute an sql update.  The executed update is defined by calling
         *  setSqlQuery prior to this method.  The database connection to be used
         *  is defined by calling setConnection prior to this method. */
        public int executeUpdate() throws SQLException
         // Define the local variables that will be used in this method
         int rowsAffected = -1;
         // Done local variables
         if(this.sqlValues!=null && this.sqlValues.length>0)
             /* A prepared update needs to be executed because the
              * sqlQuery is going to contain ? placeholders rather than
              * actual values.  It is necessary to replace these place
              * holders with their corresponding values.*/
             rowsAffected = executePreparedUpdate();
         else
             // We just need to execute a regular sql query
             rowsAffected = executeRegularUpdate();
         return(rowsAffected);
        /** If a prepared statement is needed this method will be called by the
         *  executeQuery method.*/
        private ArrayList executePreparedQuery() throws SQLException
         // Define the local variables that will be used within this method
         ResultSet rs = null;
         PreparedStatement pstmt = null;
         ArrayList data = null;
         // End local variables
         try
             pstmt = this.dbConnection.prepareStatement(this.sqlQuery);
             setSqlValues(pstmt, this.sqlValues);
             rs = pstmt.executeQuery();
             /* Closing the PreparedStatement is going to cause the
              * ResultSet to be inaccessible.  Therefore it is necessary to
              * move the data that has just been aquired into an alternate
              * data storage object.*/
             data = processResult(rs);
             // Clean up all of the db resources we have opened
             rs.close();
             rs = null;
             pstmt.close();
             pstmt = null;
             this.dbConnection.close();
             this.dbConnection = null;
             /* No exceptions are caught.  They should be dealt with by the
              * calling class. */
         finally
              /* If an exception was thrown during the execution of the
               * sql query there will still be open db resources.  They need
               * to be closed. */
             if(rs!=null)
              try
              { rs.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              rs = null;
             if(pstmt!=null)
              try
              { pstmt.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              pstmt = null;
             if(this.dbConnection!=null)
              try
              { this.dbConnection.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              this.dbConnection = null;
             /* Regardless of what happens we need to return an array of Objects.
              * If the returning value is null it should be handled by the
              * calling class. */
         return(data);
        /** If a regular sql statement is required this method will be called
         *  by the executeQuery method. */
        private ArrayList executeRegularQuery() throws SQLException
         // Define the local variables that will be used within this method
         ResultSet rs = null;
         Statement stmt = null;
         ArrayList data = null;
         // End local variables
         try
             stmt = this.dbConnection.createStatement();
             rs = stmt.executeQuery(this.sqlQuery);
             /* Closing the Statement is going to cause the ResultSet to be
              * inaccessible.  Therefore it is necessary to move the data
              * that has just been aquired into an alternate data storage
              * object.*/
             data = processResult(rs);
             // Clean up all of the db resources we have opened
             rs.close();
             rs = null;
             stmt.close();
             stmt = null;
             this.dbConnection.close();
             this.dbConnection = null;
             /* No exceptions are caught.  They should be dealt with by the
              * calling class. */
         finally
              /* If an exception was thrown during the execution of the
               * sql query there will still be open db resources.  They need
               * to be closed. */
             if(rs!=null)
              try
              { rs.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              rs = null;
             if(stmt!=null)
              try
              { stmt.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              stmt = null;
             if(this.dbConnection!=null)
              try
              { this.dbConnection.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              this.dbConnection = null;
         return(data);
        /** If a prepared update is needed this method will be called by the
         *  executeUpdate method.*/
        private int executePreparedUpdate() throws SQLException
         // Define the local variables that will be used within this method
         PreparedStatement pstmt = null;
         int rowsAffected = -1;
         // End local variables
         try
             pstmt = this.dbConnection.prepareStatement(this.sqlQuery);
             setSqlValues(pstmt, this.sqlValues);
             rowsAffected = pstmt.executeUpdate();
             pstmt.close();
             pstmt = null;
             this.dbConnection.close();
             this.dbConnection = null;
             /* No exceptions are caught.  They should be dealt with by the
              * calling class. */
         finally
              /* If an exception was thrown during the execution of the
               * sql update there will still be open db resources.  They need
               * to be closed. */
             if(pstmt!=null)
              try
              { pstmt.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              pstmt = null;
             if(this.dbConnection!=null)
              try
              { this.dbConnection.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              this.dbConnection = null;
             /* Regardless of what happens we need to return an array of Objects.
              * If the returning value is -1 it should be handled by the
              * calling class. */
         return(rowsAffected);
        /** If a regular sql statement is required this method will be called
         *  by the executeQuery method. */
        private int executeRegularUpdate() throws SQLException
         // Define the local variables that will be used within this method
         ResultSet rs = null;
         Statement stmt = null;
         int rowsAffected = -1;
         // End local variables
         try
             stmt = this.dbConnection.createStatement();
             rowsAffected = stmt.executeUpdate(this.sqlQuery);
             // Clean up all of the db resources we have opened
             stmt.close();
             stmt = null;
             this.dbConnection.close();
             this.dbConnection = null;
             /* No exceptions are caught.  They should be dealt with by the
              * calling class. */
         finally
              /* If an exception was thrown during the execution of the
               * sql update there will still be open db resources.  They need
               * to be closed. */
             if(stmt!=null)
              try
              { stmt.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              stmt = null;
             if(this.dbConnection!=null)
              try
              { this.dbConnection.close(); } catch(SQLException sqle)
              { } // EXCEPTION IGNORED
              this.dbConnection = null;
         return(rowsAffected);
        /** used to iterate through the sql values and add them to the
         *  prepared statement object. */
        private void setSqlValues(PreparedStatement ps, Object[] values) throws SQLException
         for(int i=0;i<this.sqlValues.length;i++)
             Object o = this.sqlValues;
         /* SQL starts counting at 1 not 0, so this loop needs to be
         * incremented by 1 for the setObject method to interpret it
         * correctly. */
         ps.setObject(i+1, values[i]);
    /** Used to copy a result set into a persistent object so that it can
    * be used even once the connection to the database has been closed. */
    private ArrayList processResult(ResultSet rs) throws SQLException
         ArrayList data = new ArrayList();
         ResultSetMetaData rsmd = rs.getMetaData();
         int colCount = rsmd.getColumnCount();
         while(rs.next())
         Object[] currentRow = new Object[colCount];
         for(int i=0;i<colCount;i++)
              currentRow[i] = rs.getObject(i+1); //SQL starts at 1 not 0
         data.add(currentRow);
         return(data);
    Thanks for the input,
    Ryan

    I think I have an idea of what you mean. I just want to make sure before I write everything though. I could implement your idea by doing the following right?
    I haven't tried any of this, so if there's minor (syntax) errors just ignore them. I'll fix them later.
    1. Create the following Interface.
    package com.vacode.beans.sql;
    public interface GruntBeanProccessingModule
        public Object get(Object[] properties);
    }2. Force the subclasses to implement the above interface
    public class EmployeeProcessor implements GruntBeanProcessingModule
        public Object get(Object[] properties)
         //make sure the input array is the right length (+ other validation, etc.)
         //create a new EmployeeBean
         //set all the EmployeeBean properties based on the input Object[]
         //return the EmployeeBean
    }3. Make the following additions to my SQLGruntBean class
    private requestedClassType = null;
    public void setRequestedClassType(Object o) // o must be an instance of the requested class
        this.requestedClassType = o;
    //if requestedClassType isn't null then create the ArrayList like this
    while(rs.next())
             Object[] currentRow = new Object[colCount];
             for(int i=0;i<colCount;i++)
              currentRow[i] = rs.getObject(i+1); //SQL starts at 1 not 0
             Class requestedClass = Class.forName(requestedClassType.getClass().getName());
             GruntBeanProcessingModule gbpm = requestedClass.newInstance();
             Object convertedData = gbpm.get(currentRow);
             data.add(convertedData);
         }Of course I'll have to handle any possible exceptions (requestedClassType isn't an instance of GruntBeanProcessingModule, etc.). I also notice the forum replaced some of my [] with <> (I've seen it before though, so you probably already know about it).
    Did I get it right or am I out to lunch :-)
    Thank you very much for the feedback,
    Ryan

  • Calling DB connection from another class

    Hi I am trying to create a method in another class to call another method that checks for userid in DB? What is the best way to set this up? I.e. calling method?
    //calling method below line
    private boolean setuserExist(String username) {
         else return false;
    public String getserExist() {
              return userexist;
    // Method being called below this line
    public boolean userExist(String username){
              boolean exist = false;
              System.out.println("in LoginDBAccess: username is " + username);
              try{
    Connection conn = dbc.getConnection();
    Statement statement = conn.createStatement();
    String query =      "SELECT User.UserID " +
                        "FROM User " +
                        "WHERE User.UserID = '" + username + "'";
    ResultSet resultSet = statement.executeQuery(query);
    System.out.println("1.1");
    ArrayList result = new ArrayList();
    while(resultSet.next()){
         //System.out.println("In While:");
    ArrayList item = new ArrayList();
    item.add(resultSet.getString("UserID"));
    result.add(item);
    System.out.println("LoginDBAccess Count: " + result.size());
    conn.close();
    if (result.size() == 1){
         exist = true;
              }catch(Exception e){
         e.printStackTrace();
              return exist;
         }

    Cross-post
    http://forum.java.sun.com/thread.jspa?threadID=603496

  • Data type size does not match values returned

    I've tried searching but couldn't find what I was looking for, sorry if this has been answered or is a duplicate.
    I am using the (Java) method below to get the column definitions of a table. I am doing this through an ODBC connection (using Oracle ODBC driver) and I have NO CHOICE in the matter.
    The problem I am having is that one particular column has a column size is smaller than the size of the data it purportedly holds (ie attendance_code = varchar size 3 but data value is "Absent". I suspect the data is actually a look up to situation, where my attendance_code column has a value of 'ABS' and Oracle goes and fetchs the "Absent" value.
    My issue is that the meta data returned from ODBC is the actual column definition (ie varchar(3) and not varchar2(10) for example).
    How do I resolve this? I do not have access to all_columns table etc. I have to do it using ODBC metadata only.
    TIA.
    public ArrayList<SchemaColumn> getColumnsForTable(String catalog,
                   String schema,
                   String tableName) {
              ArrayList<SchemaColumn> columns = new ArrayList<SchemaColumn>();
              ResultSet rs = null;
              try {
                   DatabaseMetaData metaData = connection.getMetaData();
                   rs = metaData.getColumns(catalog, schema, tableName, "%");
                   SchemaColumn column;
                   while (rs.next()) {
                        column = new SchemaColumn();
                        column.setName(rs.getString("COLUMN_NAME"));
                        column.setDataType(rs.getInt("DATA_TYPE"));
                        column.setTypeName(rs.getString("TYPE_NAME"));
                        column.setColumnSize(rs.getInt("COLUMN_SIZE")); <-------- this is the value that is coming back smaller than the data it actually returns
                        column.setDecimalDigits(rs.getInt("DECIMAL_DIGITS"));
                        column.setNumPrecisionRadix(rs.getInt("NUM_PREC_RADIX"));
                        column.setNullable(rs.getInt("NULLABLE"));
                        column.setRemarks(rs.getString("REMARKS"));
                        column.setDefaultValue(rs.getString("COLUMN_DEF"));
                        column.setSqlDataType(rs.getInt("SQL_DATA_TYPE"));
                        column.setSqlDateTimeSub(rs.getInt("SQL_DATETIME_SUB"));
                        column.setCharOctetLength(rs.getInt("CHAR_OCTET_LENGTH"));
                        column.setOrdinalPosition(rs.getInt("ORDINAL_POSITION"));
                        columns.add(column);
              } catch (Exception e) {
                   Log.getLogger().error("Could not capture table schema");
              closeResultSet(rs);
              return columns;
    Edited by: user10382699 on Apr 11, 2011 4:15 PM

    John, thanks for your reply.
    As far as I know I'm not doing anything inaccurately/incorrectly.
    The select I am using is SELECT * FROM <tableName>.
    The resultset metadata has a size of 3 for the column in question, and querying the schema also yields 3 for that column.
    I've tried recreating the situation using the Oracle XE DB, but as I am not familiar with Oracle, I do not know how to recreate this scenario (which would then lead me to test other options with ODBC).

  • Data type column size does not match size of values returned

    I've tried searching but couldn't find what I was looking for, sorry if this has been answered or is a duplicate.
    I am using the (Java) method below to get the column definitions of a table. I am doing this through an ODBC connection (using Oracle ODBC driver) and I have NO CHOICE in the matter.
    The problem I am having is that one particular column has a column size is smaller than the size of the data it purportedly holds (ie attendance_code = varchar size 3 but data value is "Absent". I suspect the data is actually a look up to situation, where my attendance_code column has a value of 'ABS' and Oracle goes and fetchs the "Absent" value.
    My issue is that the meta data returned from ODBC is the actual column definition (ie varchar(3) and not varchar2(10) for example).
    The resultset metadata has a size of 3 for the column in question, and querying the schema also yields 3 for that column.
    How do I resolve this? I do not have access to all_columns table etc. I have to do it using ODBC metadata only.
    I've tried recreating the situation using the Oracle XE DB, but as I am not familiar with Oracle, I do not know how to recreate this scenario (which would then lead me to test other options with ODBC).
    TIA.
    The select I am using is SELECT * FROM <tableName>.
    public ArrayList<SchemaColumn> getColumnsForTable(String catalog,
    String schema,
    String tableName) {
    ArrayList<SchemaColumn> columns = new ArrayList<SchemaColumn>();
    ResultSet rs = null;
    try {
    DatabaseMetaData metaData = connection.getMetaData();
    rs = metaData.getColumns(catalog, schema, tableName, "%");
    SchemaColumn column;
    while (rs.next()) {
    column = new SchemaColumn();
    column.setName(rs.getString("COLUMN_NAME"));
    column.setDataType(rs.getInt("DATA_TYPE"));
    column.setTypeName(rs.getString("TYPE_NAME"));
    column.setColumnSize(rs.getInt("COLUMN_SIZE")); <-------- this is the value that is coming back smaller than the data it actually returns
    column.setDecimalDigits(rs.getInt("DECIMAL_DIGITS"));
    column.setNumPrecisionRadix(rs.getInt("NUM_PREC_RADIX"));
    column.setNullable(rs.getInt("NULLABLE"));
    column.setRemarks(rs.getString("REMARKS"));
    column.setDefaultValue(rs.getString("COLUMN_DEF"));
    column.setSqlDataType(rs.getInt("SQL_DATA_TYPE"));
    column.setSqlDateTimeSub(rs.getInt("SQL_DATETIME_SUB"));
    column.setCharOctetLength(rs.getInt("CHAR_OCTET_LENGTH"));
    column.setOrdinalPosition(rs.getInt("ORDINAL_POSITION"));
    columns.add(column);
    } catch (Exception e) {
    Log.getLogger().error("Could not capture table schema");
    closeResultSet(rs);
    return columns;
    }

    I can't say I've ever seen a case where a column held more data than it was declared as, and would have to file that under "see it to believe it" category.
    Even if that somehow were the case, I'd expect the ODBC driver to return what the column is defined as anyway, not the data. The data changes with every row, but I'd expect the table metadata to be consistent, and refer to the table definition.
    For grins though, can you provide system.out.println output of the metadata, and also a "describe xxxx" from sqlplus if you can, where xxx is the table name?
    ie,
    while (rs.next()) {
    System.out.println("column name is " + rs.getString("COLUMN_NAME"));
    System.out.println("data type is " + rs.getInt("DATA_TYPE"));
    ..etc..
    Greg

  • Failed to RowUpdate to 2 different tables simultaneously

    Hi there,
    I am trying to update two different tables from each other after some calculation (this is related to inventory cost calculation) while I am using a 3rd table to drive the loop. Unfortunately, the following exception is occured..
    Place 2o: transactionQty....>>>>:353975.0 onHandQty:844259.0
    Rolled Back
    java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Row update failed.
    at com.microsoft.jdbc.base.BaseExceptions.createException(Unknown Source)
    at com.microsoft.jdbc.base.BaseExceptions.getException(Unknown Source)
    at com.microsoft.jdbc.base.BaseImplUpdatableResultSet.executeStatement(Unknown Source)
    at com.microsoft.jdbc.base.BaseImplUpdatableResultSet.updateRow(Unknown Source)
    at com.microsoft.jdbc.base.BaseResultSet.updateRow(Unknown Source)
    at updateInventoryCostData(InteIc.java:915)
    I can e-mail you the java file if any one want to help me.
    Can any one help me?
    Regards,
    Mortoza
    [email protected]

    Also, here is an example of handling transactions
    I believe this link may help:
    http://www.webservertalk.com/archive135-2005-3-934206.html
    public ArrayList myFunction(){
    Connection conn=null;
    PreparedStatement pstmt1= null;
    ResultSet resultSet=null;
    ArrayList list1;
    try{
    list1=new ArrayList();
    conn= dataSource.getConnection();
    conn.setAutoCommit(false);
    pstmt1= conn.prepareStatement();
    resultSet= pstmt1.executeUpdate();
    while(resultSet.next()){
    arrayList.add(resultSet.getString("lastName");
    conn.commit();
    return arrayList;
    } catch (SqlException e){
    if(conn!=null)
    conn.rollback();
    e.printStackTrace();
    } finally {
    if(conn!=null)
    conn.setAutoCommit(true);//must ensure this is done first because
    //following lines might throw an error
    if(rsultSet!=null)
    resultSet.close();
    if(pstmt1!=null)
    pstmt1.close();
    if(conn!=null)
    conn.close();
    }

  • Sjds2 and Java studio creator 2

    Hello
    is there a particular download version of Java studio creator 2 for JDS2?
    In the Studio Creator prerequisites document for linux, the supported OS is Red hat linux
    regards
    Raul

    Hi Abdelkrim,
    Try to place variable ArrayList mySelectedXXX
    to SessionBean and change your prerender code to something like that to reflect changes:
    //prerenderer method
    // you need this check in order to execute this code only first time page is rendered
    if (getSessionBean1().getMySelectedXXX() == null) {
        getSessionBean1().setMySelectedXXX(new ArrayList());
        while (resultSet.next()) {
            getSessionBean1().getMySelectedXXX().add(new Long(resultSet.getLong("id_XXX")));
        checkboxGroup1.setSelected(getSessionBean1().getMySelectedXXX());
    }Also you'll need to execute getSessionBean1().setMySelectedXXX(null); when you leave the page.
    Roman.

  • Solaris 10 and Java Studio Creator 2

    Hi all,
    I'm used to work with Netbeans 5.0 and Creator 2 at the same time, which caused no trouble on Linux, but since I switched to Solaris 10 (on the same machine 1 GByte RAM, Intel Pentium IV 2.4 GHz) Creator freezed if I try to start NetBeans.
    For me it is not clear whether this is a Solaris or Creator 2 issue, therefore I'm going to post this at the Creator forum as well.
    Stephan

    Hi Abdelkrim,
    Try to place variable ArrayList mySelectedXXX
    to SessionBean and change your prerender code to something like that to reflect changes:
    //prerenderer method
    // you need this check in order to execute this code only first time page is rendered
    if (getSessionBean1().getMySelectedXXX() == null) {
        getSessionBean1().setMySelectedXXX(new ArrayList());
        while (resultSet.next()) {
            getSessionBean1().getMySelectedXXX().add(new Long(resultSet.getLong("id_XXX")));
        checkboxGroup1.setSelected(getSessionBean1().getMySelectedXXX());
    }Also you'll need to execute getSessionBean1().setMySelectedXXX(null); when you leave the page.
    Roman.

Maybe you are looking for

  • Help opening a PDF file via my email on iPhone 3gs

    Does anyone know how to do this?

  • Storage space lost

    After upgrading to iOS 5 4.7 GB storage space is used up by "others". What could be the reason for this?

  • Header in SAPquery

    Hi all, I have SAPquery in which i need to use one  varible in header and footer text so as get that variable value in output dynamically. can we write any varibels other than &%NAME   &%DATE    &%TIME    &%PAGE in header and footer  . please give me

  • Booking Transportation Cost in to Material

    hi Guys we are purchasing  HSD from Indian Oil.  we giving 2 Type Purchase Orders 1- HSD   2 - Transporation Vedors Transporation Vendors may be 3- 4 vendors  can supplying HSD to our company. Every Vendors can be supply  5 times each. we are making

  • Why exporting eps from InDesign isn't working?

    I'm trying to export a brochure cover from InDesign as an eps to open in PhotoShop (to create web image). The eps won't open in PhotoShop. I've also tried exporting the cover page as a jpeg. This will not open in PhotoShop either. The message says it