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.

Similar Messages

  • In IOS7; I am trying to delete a picture from an old text message conversation, and it keeps coming back in a second. Why?

    In IOS7; I am trying to delete a picture from an old text message conversation, and it keeps coming back in a second. Why?

    Turn off, and on your device again; and how are you deleting the picture?b From where :O

  • 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

  • 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;
    }

  • How to retrieve deleted text conversation on iphone 4s not backed up. Deleted by mistake

    how can I retrieve a deleted text conversation on iphone 4s which was not backed up. It was deleted by accident. Is there anyway I can do this?

    If you do not have a backup, there is no way to retrieve the messages.
    ~Lyssa

  • 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.

  • 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

  • I upgraded from iPhone 3GS to iPhone 6.  Everything converted fine until I deleted an app in error.  When I downloaded it from iTunes, my account is no longer recognized by the app's host servers.  Can I go back and re-sync one app from my old phone?

    I upgraded from iPhone 3GS to iPhone 6.  Everything converted fine.  Yesterday I deleted an app in error.  When I downloaded the software it from iTunes ( did this many times on the old 3GS), my account is no longer recognized by the app's host servers (Playtika), even though it did after the initial conversion.  Can I go back and re-sync just one app from my old phone?  

    Try deleting what is called the iPod Photo Cache. 
    http://support.apple.com/kb/TS1314

  • 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;
    }

  • Mac Mail conversation grouping

    Hi Guys,
    I would like to group my mail messages from the sender rather than the conversation title. Using the email title as a sorting reference seems to lead to emails from other people dropping into other converstions. I want to group conversations to individuals not a title... can this be done if so how?
    Thanks
    Stuart

    interestingly enough, i do have that checked.  It sorts the conversations and emails on the left pane, but within each conversation.  HOWEVER, when i uncheck/check that setting within a conversation, the conversation does flip to the most recent email.  When i click out of the conversation, and back into, it does not.  i just right clicked and marked my "3000+" unread emails as "read."  Having all emails "read" does keep you at the top of the conversation. 
    I tried testing your theory that it jumps to the most recent read, by clicking an unread within the conversation. After clicking out/back into the conversation, I was not set on that specific email. I can't figure out its logic frankly.  I guess i could understand if it defaulted to the oldest unread email actually, but it's not dong that either.  thanks for your responses.  I really think a nice feature would be to default to the most recent unread email.   The triangle trick is nice though. For now, i will "try" and be more diligent about marking emails as they come in

  • 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%'.

  • Mac mail lion resets organize by conversation

    I just upgraded my MacBook Pro (2.4 GHz Intel Core 2 Duo) to Lion and there seems to be a bug in Mail where despite my repeatedly unchecking the "organize by conversation" option, it keeps defaulting back to this.  I cannot figure out what to do to make it STAY unchecked -- I absolutely LOATHE "organize by conversation" and just want to use classic view without this and stay sorted by date received.  Can someone please help me with this?

    I found something similar to this, but I had to uncheck 'organize by conversation' for every folder. Once this was done, it stayed unchecked . But, I've just upgraded to Mountain Lion and it's worse; smart folders don't stay unchecked (neither do VIP's).
    I also tried to check 'use classic layout' in preferences, but the mail program crashes immediately I click the check box

  • Resultset.next() Issue

    Okay I have narrow my issue down to activity involved with the resultset.next() method. What is happening is I am working through a small resultset--3 records. These records are made up of columns from 3 seaprate tables (9 total). Some of these tables have many records (> 3K) in them. I moved the SQL statement in a store procedure so we can execute the query in a faster manner. The store procedure is returning the information in only 46ms. However, when I start looking through the resultset on the app server, it is taking 19K ms for the first time through the loop.
    I am at a lost to explain why the first iteration is taking so long. I have looked back at the SQL statement. I use alias names for the tables. I identify the column names in the select statement, but I do not use aliases for the column names. I am wondering if my problem is connected to the fact that the Oracle Driver
    maybe going back to get the column names the first time through the result set. I am not using the column name to index into the resultset. If my theory is right, this would explain the high latency. If I am wrong, I am stumped.
    Any suggestions or help explaining this would be greatly appreciated.
    As always, thanks for reading my post.
    Russ

    Execution of a CallableStatement (Procedure) is relatively fast. Getting ResultSet back is fast. But First iteration over the result set takes a lot of time comparing to the following iterations.
    Part of the code :
    long start=System.currentTimeMillis();
    int i=0;
    long local=System.currentTimeMillis();
    while(rs.next()){
    if (i==0){
    MetricsUtil.printTime("ResultSetRowHolder.getRows(ResultSet rs) ["+list.size()+" ]",local);
    local=System.currentTimeMillis();
    hol=new ResultSetRowHolder(rs);
    list.add(hol);
    i++;
    if (i%100==0){
    MetricsUtil.printTime("ResultSetRowHolder.getRows(ResultSet rs) ["+list.size()+" ]",local);
    local=System.currentTimeMillis();
    MetricsUtil.printTime("ResultSetRowHolder.getRows(ResultSet rs) ["+list.size()+" ]",start);
    Printouts
    Metrics << QueryHelper.executeStatement() >> Total time -> 2.836 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [0 ] >> Total time -> 13.867 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [100 ] >> Total time -> 0.48 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [200 ] >> Total time -> 0.44 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [300 ] >> Total time -> 0.47 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [400 ] >> Total time -> 0.38 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [500 ] >> Total time -> 0.37 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [600 ] >> Total time -> 0.38 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [700 ] >> Total time -> 0.35 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [800 ] >> Total time -> 0.34 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [900 ] >> Total time -> 0.32 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [1000 ] >> Total time -> 0.34 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [1100 ] >> Total time -> 0.41 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [1200 ] >> Total time -> 0.32 sec
    Metrics << ResultSetRowHolder.getRows(ResultSet rs) [1230 ] >> Total time -> 14.340 sec

  • 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();
    }

  • Serialization Back to Database

    Hi Every one, I am facing a little problem here that i cant seem to get past.
    I have done Serialization on my Database, i can Read the File into a Text Area. inside my View. I am using MVC in my program. What i am having a problem with is Trying to get this Object that i had Created with Serialization Into my Database as a Backup
    My Database Table is made up with the following
    ID (Int)
    FirstName (text)
    LastName (text)
    Address (text)
    PhoneNumber (int)
    bytes (blob)
    WRITE_OBJECT_SQL_PATIENT =
                             connection1.prepareStatement("INSERT INTO Patient(Id,FirstName,LastName,Address,PhoneNumber,bytes)" +
                                       "VALUES(?,?,?,?,?,?)");
         public ArrayList<Person> writeJavaObject(ActionEvent evt)
              ArrayList<Person> results = null; // ArrayList <Person>
              ResultSet resultSet = null; // ResultSet Set to Null
              try
                   // executeQuery returns ResultSet containing matching entries
                   resultSet = WRITE_OBJECT_SQL_PATIENT.executeQuery(); //ResultSet equals SelectAllPeople & Execute The Query Above
                   results = new ArrayList< Person >(); // Placing Entries into ArrayList
                   WRITE_OBJECT_SQL_PATIENT.setString( 1,"Patientid");
                   WRITE_OBJECT_SQL_PATIENT.setString( 2, "FirstName" );
                   WRITE_OBJECT_SQL_PATIENT.setString( 3, "LastName" );
                   WRITE_OBJECT_SQL_PATIENT.setString( 4, "Address" );
                   WRITE_OBJECT_SQL_PATIENT.setString( 5, "PhoneNumber" );
                   WRITE_OBJECT_SQL_PATIENT.setObject( 6, "object" );
              } // end try
              catch ( SQLException sqlException )
                   sqlException.printStackTrace();
                   close();
              } // end catch
              return results;
         }This is a Method that is calling the above code but i am getting Can not issue data manipulation statements with executeQuery().
         public static void LOADITEMactionPerformed(ActionEvent evt)
              results -
                            DBSQLQueries.writeJavaObject(evt);
         }

    I doubt that design will be usable over time. As an example of why - because data model entities are not always mappable in one to one relationships.
    And given that it looks like the connection/statement scope is outside the method it probably isn't thread safe either. And perhaps leaking connections.
    Other than that your question is a bit hard to understand. I can only suppose that when you attempt the write that it fails but you don't specify how. In other words you do not supply the exception and stack trace.
    But as a guess you are not using an updatable query.

Maybe you are looking for

  • Successful Windows 7 install (mostly)

    I would like to report that I have been successful at installing Windows 7 RC on a dedicated drive on a Mac Pro (early 2008) using the following procedure: 1. Downloaded the ISO (Windows 7 RC 32-bit) from Microsoft and burned the image to DVD using N

  • Error ocurring when trying to Backup catalog in PSE 7

    I am about to upgrade my OS and want to start fresh.  Obviously, I want to backup my PSE 7 catalog beforehand so I can restore it and not lose the thousands of tags, etc I have applied.  I have carefully followed the steps and even ran some utilities

  • IC Webclient Profiles

    Hi, we started customizing the IC Webclient trough profiles (as described in the "Consultant's Cookbook for IC Webclient CRM 4.0", Chapter 3). Assigning profiles seem to work, but the profile xml-tags in the profile ("<ControllerReplacements>") don't

  • Performance issues post SAN & server Migration

    Hello everyone, We have recently migrated our SAN  from Emc san ( FC with 4gbe) to dell san (Iscsi with 1gbe) ..2 ports on the the dell san have been teamed up as one ...Also we migrated our Sap app & ibm db2 9.1 db from ibm p5 to p7 server ...Since

  • APPLE HARDWARE TEST HELP

    I need help plz. I got a Macbook Pro (late 2011) model. In my Macbook Pro APPLR HARDWARE TEST is not working. I tried so many pressing the D key and Option + D as well nothing seems to work. It logs as normal. Plz apple help me... Onece when I went t