ResultSet question

Hi Developers,
I have a question about copying of a resultset object into another ResultSet object. To make it much clear of what I am trying to do, I am retreiving a particular row by using absolute(int) method in a given Scrollable ResultSet object(rs1).Now I want to store somehow the values of that particular row only in a ResultSet object only(either rs1 or in a different one).For this, I was trying to use another Scrollable ResultSet object(rs2) and copy the contents(just 1 one row) in the manner(rs2=rs1).The main reason that I am trying to store them in a ResultSet object is beacuse I have a helper package which takes that particular ResultSet object and displays it. I am having trouble copying in this manner.Could anyone please suggest me a method for doing this or let me know of where exactly I was going wrong?
Thanking you,
Ashwin

It would be extremely difficult for you to create a ResultSet object, because ResultSet is an interface that would require you to define over 100 methods. The only practical method for getting a ResultSet is to ask the driver to give you one; the programmers of the driver have already done all that hard work defining a ResultSet implementation. And the only way to get a ResultSet from a JDBC driver is to use Statement (or PreparedStatement or CallableStatement) and call its executeQuery() method. In other words, have the driver execute the query that returns the results you need.
On second thought, why do you need another ResultSet object? Why can't you just give rs1 to your helper package?

Similar Messages

  • ResultSet question Please help!!!!!!!!

    Hi, i have the following code to send a query to a mysql database, that counts the number of rows in a certain table:
    ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM PROJNOREG");
    How can I convert the value to an Int? I've tried to capture the value by using rs.getString(), but this doesn't work because you have to specify a column name if you use getString. For example, rs.getString("NAMES") retrieves the values from the column NAMES. But all I want is the number of rows, and I use a valid SQL statement as you can read above, but I don't know how to convert the value to a string of Int. Any ideas?

    I dislike using indices. if you insert a field (in
    your query), you have to remap all your indices.True. I'm not an expert but I play one on TV.
    No, really, It is a matter of personal style but I like to be explicit in the SQL call that gets the data.
    // Don't like
    String SQL = "Select * from MyTable;";
    // Do Like
    String SQL = "Select a,b,c,d from MyTable;";.. this way even if the db changes under me my data is still in the order that I want so the indicies work for me.

  • JDBC Driver: MS Access

    I need to connect locally to a mdb file on a Windows OS and manipulate its data. I have tried the sun.jdbc.odbc.JdbcOdbcDriver but it does not support primary keys manipulation. I have read numerous topics about JDBC drivers for MS Access, some of them also in this forum. The suggested drivers I found so far are commercial; I definitely need a non-commercial one for testing purposes. So please do not respond to this post, advertising commercial drivers (like HXTT for example).
    I've had a look at http://jackcess.sourceforge.net/ but it requires specific code syntax and I would like to use a driver without rewriting my application. Then I've found http://rmijdbc.objectweb.org/ but it only allows remote access to an already existent JDBC driver.
    Any suggestion about a non-commercial JDBC driver for MS Access? Thanks in advance.

    When I try:java.sql.ResultSet rs_PrimaryKeys =
    Database_MetaData.getPrimaryKeys(null, null,
    for_TableName); with the
    sun.jdbc.odbc.JdbcOdbcDriver, it's reported that "the
    driver does not support this operation yet". Right, but that doesn't mean you can't work around it.
    Besides,
    it does not allow to do
    rs_Columns.getString("sameIntValueHere");more than one time within the same rowwise iteration
    of rs_Columns.next()
    There's no workaround for that. It's just the nature of streams/iterators/cursors.
    Any
    ideas/suggestions for a workaround will be more than
    gladly received! This issue is causing me headaches
    for days and I've finally decided to share my
    struggle here...You can work around the primary key problem.
    As far as the ResultSet question goes, you should not be using ResultSets that way. Iterate through the ResultSet, load the data into an object or data structure, and close it right away in the narrowest scope possible.
    %

  • MDM iView resultset problem and question about eventing

    Hi experts,
    I created a MDM iView resultset for my main table as search table (comparison is not supported). When I click on preview I get an empty table ("Found <Tablename>: 0 of 10", table contains 10 entries at the moment). I tried the same with a subtable and everything works fine (all entries have been in the preview table). Any ideas why I don't get a result?
    My 2nd question: can I choose the parameter name in eventing (EPCF) on my own? So if I have Vendor_Id as field can I use vendorid as parameter name? Do I have to define anything in the listener iView (e.g. in detail iView for an event from resultset iView)? Maybe you have a useful tutorial link (please not SAP help section)?
    Thanks for your answers.
    Regards, bd

    It is possible to retrieve the number of rows from a resultset --
    Statement stmt= con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                                        ResultSet.CONCUR_READONLY);
    ResultSet rs= stmt.executeQuery("<your select query here>");
    int totalRows;
    if (rs.last()) // can it move to the last row?
       totalRows= rs.getRow(); // get its row number
    else
       totalRows= 0; // no rows in the resultset
    rs.first() // set the cursor back to the startNote that the resultset has to be scrollable (TYPE_SCROLL_INSENSITIVE).
    kind regards,
    Jos

  • A question for resultset to get data in td

    Dear all
    one of question to get data from resultset , for example in i have some data in database , the data type like this ,
    product : a 1
                     a 2
                     b 1
                     b 3 how i the idea of method i can display that result in my jsp
    <td rowspan="4" align="center" bgcolor="#FFFF99" style="padding-left: 6px; padding-right: 6px; padding-top: 5px; padding-bottom: 3px">product A</td>
       </tr>       
                                      <td align="center" bgcolor="#FFEBD7" style="padding-left: 6px; padding-right: 6px; padding-top: 5px; padding-bottom: 3px">1</td>
                                    </tr>
                                    <tr>
                                      <td align="center" style="padding-left: 6px; padding-right: 6px; padding-top: 5px; padding-bottom: 3px">2</td>
                                    </tr>

    i use custom tag to achieve this project .
    which way can you suggest to do it .
    for example
    String[] groupanmes = new String[1000];
    conn = DriverManager.getConnection("proxool.myDB");
         if(conn !=null){
              stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
              rst  = stmt.executeQuery("select * from salegroup where username ='"+user+"'");
           int i =0;                      
           while(rst.next()){
              groupanmes[i] = rst.getString("GROUPNAME");
            i++;
           }//end if     Message was edited by:
    roger5089

  • A question about ResultSet.UpdateObject(int column, Object x)

    hi, I write some code which use the TableModel to represent the data fetched from MS-ACCESS.
    the problem is about the UpdateObject(...) method which is in the implement of the AbstractTableModel method setAtValue(). when transfered OBJECT TYPE is java.lang.String, I can't get the correct result in the JTable view.
    my code is as below, could somebody point me out my problem
    public class MyTableModel extends AbstractTableModel {
        private ResultSet rs ;
        private ResultSetMetaData rsmd;
        /** Creates a new instance of MyTableModel */
        public MyTableModel() {
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            String url = "jdbc:odbc:CoffeeBreak";
            try {
                Connection con = DriverManager.getConnection(url,"","");
                String strSQL = "SELECT * FROM COFFEES";
                Statement pSt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
                rs = pSt.executeQuery(strSQL);
                rsmd = rs.getMetaData();
            } catch (SQLException ex) {
                ex.printStackTrace();
    /* table model retrieve the Class type of a column method here*/
    public Class getColumnClass(int c){
            try {
                return Class.forName(rsmd.getColumnClassName(c+1));
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return String.class;
    //method of update database and JTable after user edited a table cell
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            try {
                int concurrency = rs.getConcurrency();
                if(concurrency == 1008){
                    rs.absolute(rowIndex+1);    //the JTable row index is start from 0,so plus 1
                    rs.updateObject(columnIndex+1, aValue);//the JTable column index is start from 0, so plus 1
                    rs.updateRow();
            } catch (SQLException ex) {
                ex.printStackTrace();
        }when the column type is about java.lang.String, the cell's result is incorrect, it looks like "[B@1f8f72f" and database can't update.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    It's me again.
    I post the whole class code here
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.AbstractTableModel;
    * @author qhj
    public class MyTableModel extends AbstractTableModel {
        /** Creates a new instance of MyTableModel */
        private ResultSet rs ;
        private ResultSetMetaData rsmd;
        private Statement pSt;
        private String strSQL;
        public MyTableModel() {
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            String url = "jdbc:odbc:CoffeeBreak";
            try {
                Connection con = DriverManager.getConnection(url,"","");
                strSQL = "SELECT * FROM COFFEES";
                pSt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
                rs = pSt.executeQuery(strSQL);
                rsmd = rs.getMetaData();
            } catch (SQLException ex) {
                ex.printStackTrace();
        public int getRowCount() {
            try {
                rs.last();
                return rs.getRow();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return 0;
        public int getColumnCount() {
            try {
                return rsmd.getColumnCount();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return 0;
        public Object getValueAt(int rowIndex, int columnIndex) {
            try {
                rs.absolute(rowIndex+1);
                return rs.getObject(columnIndex+1);
            } catch (SQLException ex) {
                ex.printStackTrace();
            return null;
        public String getColumnName(int column){
            try {
                return rsmd.getColumnName(column+1);
            } catch (SQLException ex) {
                ex.printStackTrace();
            return "N/A";
        public Class getColumnClass(int c){
            try {
                return Class.forName(rsmd.getColumnClassName(c+1));
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return String.class;
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            return true;
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            try {
                int concurrency = rs.getConcurrency();
                if(concurrency == 1008){
                    rs.absolute(rowIndex+1);
                    rs.updateObject(columnIndex+1, aValue);
                    //rs.updateRow();
                    //rs = pSt.executeQuery(strSQL);
            } catch (SQLException ex) {
                ex.printStackTrace();
            fireTableDataChanged();
    }

  • Question about updateRow in ResultSet

    Simple problem. When I update the values in a resultset with:
    rs.updateString("columnName", aString);
    rs.updateRow();the value of columnName is updated, but the values of all the other columns in the row are set to nothing. How do I prevent this from happening? Do I have to update all the column values when using updateRow, i.e getting the values from the resultset and then updating with the same values?
    - Karl XII

    Hi Karl,
    You could try using the following code:
    int numRows = 0;
    int empId = 1223;
    String updateEmp="update employees set department=?
    where id = ?";
    PreparedStatement pstmt =
    conn.prepareStatement(updateEmp);
    pstmt.setString(1,"department");
    pstmt.setInt(2,empId);
    numRows = pstmt.executeUpdate();
    pstmt.close();
    This piece of code would only update the columns that
    you mention in the PreparedStatement SQL query.
    Thanks,
    Rashmi.Thanx. But I have a resultSet that is linked to the database. I to only like to edit the value of a specific column in the resultset... any other suggestions?

  • Question about resultset

    Hi,
    I have a simple problem. I wish to move data from a resultset to a string[]. However, I do not know the number of rows in the resultset.
    I have tried something like this:
    while (resultset.next()) {
                while ( (sqlData[rowCount++] = resultset.getString(++colCount))){}
                           colCount = 0;
    }Javac said it expected a boolean and not a string. Well of course it requiers a boolean, but isn't a boolean returned if the operation on the resultset isn't possible?
    All help appriciated...
    Karl XII

    It is possible to retrieve the number of rows from a resultset --
    Statement stmt= con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                                        ResultSet.CONCUR_READONLY);
    ResultSet rs= stmt.executeQuery("<your select query here>");
    int totalRows;
    if (rs.last()) // can it move to the last row?
       totalRows= rs.getRow(); // get its row number
    else
       totalRows= 0; // no rows in the resultset
    rs.first() // set the cursor back to the startNote that the resultset has to be scrollable (TYPE_SCROLL_INSENSITIVE).
    kind regards,
    Jos

  • Same old...number of rows in a resultset...but a different question

    Hi,
    I'm writing a code to generate report from the database. Everything is working absolutely fine. Now the problem is that when I try to check whether any row has been returned, I'm not able to do it correctly. What is happening is that the column heading is also being considered as a data and being written to the output file. I want that if there is no data ( excepting the column headings ) the program should terminate. Can anyone help me out of this? Thanks & regards,
    Faisal

    Hi,
    Plz find the code below :
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    public class JDBC8
         public static void main (String[] args) throws Exception
                        Connection con = null;
                        final String query = "select TNAME,TABTYPE from tab where tname like '%FAZ%'";
                        Statement stmt = null;
                        int ctr=0;
                        int maxColLength = 0;
                        String fileName = "";
                        ResultSet rs = null;
                        FileNameCreater obj = new FileNameCreater();
                        fileName = obj.getFileName();
                        int t = 0;
                        System.out.println("Created file : " +fileName);
                        try {
                             // load the driver
                                  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        catch (java.lang.ClassNotFoundException e)
                                  System.err.print("ClassNotFoundException.");
                                  System.err.println(e.getMessage());
                        System.out.println("Connecting to the database. Please wait....");
                        try {
                                       // define the connection URL. establish the connection.
                                       con = DriverManager.getConnection("jdbc:odbc:DSN1","mis","abcdef#0");
                                       if ( con.isClosed() )
                                       System.out.println("Failed to connect to the database. Press enter to continue.");
                                       System.in.read();
                                       else
                                       System.out.println("Connected to the database.");
                                       System.out.println("Processing...Please be patient...");
                                       // create a statement object
                                       stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
                                       // Execute a query
                                       rs = stmt.executeQuery(query);
                                       ResultSetMetaData rsmd = rs.getMetaData();
                                       rs.first();
                                       System.out.println("check 1 = " + rs.getRow());
                                       System.in.read();
                                       int cntr = 0;
                                       String tempStr = "";
                                       String tempLbl = "";
                                       boolean flag = false;
                                       boolean inWhile = false;
                                       rs.beforeFirst();
                                       while ( rs.next() )
                                            System.out.println("entered while");
                                            System.in.read();
                                            tempStr = rs.getString(++cntr);
                                            tempLbl = rsmd.getColumnLabel(cntr);
                                            System.out.println("cntr = " + cntr + " tempStr = " + tempStr + " tempLbl = " + tempLbl);
                                            if ( tempStr == tempLbl )
                                                 flag = true;
                                            else
                                                 flag = false;
                                            inWhile = true;
                                       if ( inWhile )
                                                 rs.beforeFirst();
                                                 FileWriter writer = new FileWriter(fileName);
                                                 BufferedWriter buf_Writer = new BufferedWriter(writer);
                                                 System.out.println("Processing started...");
                                                 int colCount = 0;
                                                 colCount = rsmd.getColumnCount();
                                                 String colLabel = "";
                                                 for ( int x = 1; x <= colCount; x++ )
                                                      colLabel = rsmd.getColumnLabel(x);
                                                      buf_Writer.write(colLabel);
                                                      if ( x < colCount )
                                                           buf_Writer.write("|");
                                                 buf_Writer.newLine();
                                                 rs.beforeFirst();
                                                 // Process the results
                                                 while(rs.next())
                                                 ctr++;
                                                      for (int i = 1; i <= colCount; i++)
                                                           String columnValue = rs.getString(i);
                                                           buf_Writer.write(columnValue);     
                                                           if ( i < colCount )
                                                                buf_Writer.write("|");               
                                                      buf_Writer.newLine();
                                                 buf_Writer.close();
                             catch (SQLException e)
                                  System.err.println("SQLException : " + e.getMessage());
                             finally
                                  try
                                       // Close the resultset, statement and connection objects.
                                            if (rs != null)
                                                 rs.close();
                                            if (stmt != null)
                                                 stmt.close();
                                            if (con!=null)
                                                 con.close();
                                       catch(Exception ex)
                                            System.out.println("Exception encountered: "+ ex.getMessage());
                                  System.out.println("Program completed successfully.");
    } // end of main
    } // end of class

  • Question on ResultSet

    I want to assign the values of the rows to an array, so I need
    to initialize the array before assigning them values.
    Is there any method for getting the total number of rows
    of the ResultSet?
    Thanks

    A ResulSet has an accessible ResultSetMetaData member.
    However - the ResultSet object has a limitation to the number of records it holds at any one time depending on the size specified prior to the query.
    Options are - use a dynamic storage class, (Vector), or use the same arguments to retrieve a COUNT result and use that to init the array.
    Personal preference would be to use a java.util.Vector.

  • A question about ResultSet

    Does anyone can tell me how to use ResultSet.getDate(String field, Calendar cal)method,, I have tried many way,,, but if I use this method, everytime throw a AbstractMethodError... thanks

    Calendar calendar = Calendar.getInstance();
    while(rs.next){
    rs.getDate("SYSDATE", calendar);
    and SYSDATE is a kind of DATE
    java.lang.AbstractMethodError occur while I run
    rs.getDate() Method ..
    is this a bug of java???It may simply be that the driver you are using doesn't support this method. Which driver and version are you using?
    Col

  • Question about ResultSet Columns

    Do resultset columns start at index 0 or 1???

    From the [url http://java.sun.com/j2se/1.5.0/docs/api/java/sql/ResultSet.html]API docs
    The ResultSet interface provides getter methods (getBoolean, getLong, and so on) for retrieving column values from the current row. Values can be retrieved using either the index number of the column or the name of the column. In general, using the column index will be more efficient. Columns are numbered from 1. For maximum portability, result set columns within each row should be read in left-to-right order, and each column should be read only once.

  • Resultset, preparedstatement question. what is first..

    Hello.
    My English ability is very poor. sorry
    Usually
    I did...
    Rs.close();
    pstmt.close();
    con.close();
    but
    pstmt.close();
    rs.close();
    con.close();
    is it possible....
    have no error but I want know. If resultset is alive, preparedstatement can close?
    Q 2.
    I use DBConnectionManager
    but it is nullpointer exception
    In my book
    rs.next();
    } finally {
    if (rs != null) rs.close();
    if (pstmt != null) pstmt.close();
    if(con!=null) connMgr.freeConnection("mysql",con);
    } <-- it's not close con(Connection)
    but in my another book
    con.close();
    what is correct?

    Hello.
    My English ability is very poor. sorry
    Usually
    I did...
    Rs.close();
    pstmt.close();
    con.close();
    but
    pstmt.close();
    rs.close();
    con.close();
    is it possible....
    have no error but I want know. If resultset is alive,
    preparedstatement can close?
    No. Once the statement is closed (regardless of type) the ResultSet can not be used.
    You should explicitly close everything and make sure that the result set is closed first.
    >
    Q 2.
    I use DBConnectionManager
    but it is nullpointer exception
    In my book
    rs.next();
    } finally {
    if (rs != null) rs.close();
    if (pstmt != null) pstmt.close();
    if(con!=null) connMgr.freeConnection("mysql",con);
    } <-- it's not close con(Connection)
    but in my another book
    con.close();
    what is correct?
    You are looking at two different things. In the first example it is using connection pool. The freeConnection() method returns the connection to the connection pool. In the second example there is no connection pool, so the connection must be explicitly closed.

  • 2 Questions about ResultSet

    Q1. Do I need to ( Or should I for good programming practice ) explicitly close a ResultSet ?
    Q2. Does a ResultSet contain retrieved records from the query or a list of "pointers" to records which are retrieved from the DB only as the ResultSet is walked through?
    Thanks ..... J

    Q1. Do I need to ( Or should I for good programming
    practice ) explicitly close a ResultSet ?You should, and sometimes you need to, e.g. to avoid getting a "too many open cursors" database error when using lots of ResultSets within a short span of time.
    Q2. Does a ResultSet contain retrieved records from
    the query or a list of "pointers" to records which
    are retrieved from the DB only as the ResultSet is
    walked through?Depends on the implementation. Typically, it does contain some (if not all) records. Other data (e.g. BLOBs) might be read in streaming mode.

  • Another nooblike question on DataTable and displaying ResultSets from db...

    Hey guys,
    I am trying to follow this tutorial example:
    http://www.oracle.com/technology/oramag/oracle/06-jan/o16jsf.html
    I am doing the second part of the example because the first part is not matching with what I want to do. So if you go through the code and I am sure for you gents its absolutely no problem to analyze and decipher the code. Basically I have a 2 column small table that I want to show up on the screen. I am using this as a learning example. I understand most of the code posted except for the variable 'column1' or 'column2' are. For the life of me I cannot figure out what it is. If someone can fill in the missing gap I would appreciate it. Also another part of the code that is kind of not making sense is the dataTable1.setVar("catalog"); line. Where does the author get 'catalog' from?
    Hope someone can help me out.
    Thanks in advance.
    Surya

    In this line dataTable1.setVar("catalog"); you are making a reference to your value. Inside the datatable, you will refer to the value (a register in the model) as catalog. So you can access all properties of a single register.
    Column1 and column2 are columns in the table.
    It's better to you to see first a more simple example of a datatable.
    http://www.laliluna.de/first-java-server-faces-tutorial.html

Maybe you are looking for

  • Will this hard drive work with my Mac Pro?

    Just looking for confirmation that this hard drive will work with my Mac Pro: http://www.aria.co.uk/Products/Components/HardDrives/SATA+%28Serial+ATA%29/500GB+to+1TB/Samsung+HD103SJ+SpinPoint+F3+1TB+SATA- II+3.5%22+Hard+Drive?productId=37726&page=4&r

  • Can't add to display list from a class

    in my Main.as file, this works as expected: var t:TextField = new TextField(); t.text = "hello in main"; addChild(t); However, when I create an instance of a class, and I have that same code in the constructor of that class, the text doesn't show up.

  • Set language for spell check

    iWeb marks all my Spanish text with red underlines. I see that when I click to check spelling it lets me change the dictionary to Spanish, but where can I set it to default to Spanish for this site? I just found it works if I highlight the text and c

  • JPEG IMAGE READING

    hi i want to read an jpeg image, remove the header,uncompress it and accesses its image 2d array how can i do it?

  • Unlock iPad 4 (WiFi + Cellular)

    Apple offers unlocked iPhone through its online store webpage. But, iPad is only provided with those 3 carriers. Is there any factory unlocked model or I must use other tricks to make it work?