String tokenize resultset, and a new query on tokens

Hello all,
I have to read a field from tablea , the tokenize the resulting string to get a number of strings
then i have to query tableb based on all theese string
basically i get a number of keys from tableA
then look up th ekey-value table for their values and display them.
any help on both design & code would be greatly appreciated.
i was thinking of putting the tokenized key into an array & somehow query the other tableB on that array , but am not quite sure how to do that!!
Urgent help is appreciated!!

Looks like you've found a complicated way of asking for a SQL join. If that is what you mean, the following query will do for you nicely. It will return all value2's from tableb's rows that have a match on the value in somefield with someotherfield in tablea for all rows in tablea with the specified search value.
SELECT b.value2
FROM TableA a INNER JOIN TableB b ON b.somefield = a.someotherfield
WHERE a.value1 = <your search value>
If you want each value2 to be returned at most once, even if it exists in the tables more than once, you might add the DISTINCT key word as you did in your question, but I do not see the need for that from your question.
Good luck,
Richard

Similar Messages

  • SQL Server 2012 Management Studio Displays Error With "New Query" and Intellisense Works Intermittenly

    I was upgrade to SQL Server 2012 and Visual Studio 2010 was upgraded with SP1 the same day.  This is x64 machine. 
    Microsoft SQL Server Management Studio      11.0.2100.60
    Microsoft .NET Framework      4.0.30319.261
    Operating System      6.1.7601
    Problem 1) With SQL Server Management Studio, selecting "New Query" a warning box is displayed: "The 'Microsoft.Practices.EnterpriseLibrary.Configuration.Design.VisualStudioIntegration2010Package, Microsoft.Practices.EnterpriseLibrary.Configuration.Design.VisualStudioIntegration2010,
    Version=1.0.0.0, Culture=netutral, PublicKeyToken=null' package did not load correctly.    The problem mayhave been cuased by a configuration change or by the installation of another extension.  You can get more information by running the
    application together with the /log parameter on the command line, and then examining the file ...\AppDate\Roaming\Microsoft\AppEnv\10.0\ActivityLog.xml'.  Continue to show this error message?
    Problem 2) In a Query Initellisense works intermittently but most of the time it will not display anything.  I have tried Edit|Intellisense|Refresh Cach size and also seperately, Edit | Intellisense | List Members but neither has helped.  Also
    tried different selections for Tools|options| T-SQL | Intellisense| Maximum Script Size; no luck either. 

    Hi WallyJim,
    For your first problem, possible workaround:
    In Programs and Features (or Add/Remove Programs), right click the Microsoft Enterprise Library 5.0 Optional Update 1 program and select change. Remove the VisualStudio2010 integration.
    Then, install the EnterpriseLibrary Configuration extension from Microsoft via the Extension Manager in VS2010. This will allow you to launch the configuration editor from VS2010, but will not be installed for SSMS.
    For more information, please refer to
    https://connect.microsoft.com/SQLServer/feedback/details/620532/error-message-on-new-query-window-opening.
    For your second problem, the following conditions might affect the behavior of IntelliSense:
    There is a code error above the cursor.
    The insertion point is inside a code comment.
    The insertion point is inside a string literal.
    The automatic options are turned off.
    For more information, refer to Troubleshooting IntelliSense (SQL Server Management Studio):
    http://msdn.microsoft.com/en-us/library/ms173434.aspx.
    Thanks,
    Maggie
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. This can be beneficial to other community members reading the thread.

  • Parsing and String tokenizer

    I am trying to use String Tokenizer to extract fields from a file then do a calculation on some of the fields.
    My problem is when I try to parse the strings that need the calculations I get error codes as shown at the end of post. I don't see why the parsing shouldn't work.( error codes are class expected and incompatable types)
    // ParsingTextFile.java: Process text file using StringTokenizer
    import java.io.*;
    import java.util.StringTokenizer;
    public class ParsingTextFile1 {
      /** Main method */
      public static void main(String[] args) {
       // Declare  buffered file reader and writer streams
       BufferedReader brs = null;
       BufferedWriter bws = null;
       //declare tokenizer
       StringTokenizer tokenizer;
       // Declare a print stream
       PrintWriter out = null;
        // Five input file fields:total string, student name, midterm1,
        // midterm2, and final exam score
        String line=null;
        String sname = null;
       String mid1= null;
        String mid2 = null;
        String finalSc = null;
      /  double midterm1 = 0;
        double midterm2 = 0;
        double finalScore = 0;
        // Computed total score
        double total = 0;
        try {
          // Create file input and output streams 
          brs = new BufferedReader(new FileReader("in.dat"));
          bws = new BufferedWriter(new FileWriter("out.dat"));
         while((line= brs.readLine())!=null){
         tokenizer =new StringTokenizer(line);
          sname = tokenizer.nextToken();
          mid1 = tokenizer.nextToken();
          mid2 = tokenizer.nextToken();
          finalSc= tokenizer.nextToken();
          midterm1 = double.parseDouble(mid1)//this code not working
          midterm2 = double.parseDouble(mid2);)//this code not working
          finalScore = double.parseDouble(finalScore);//this code not working
          out = new PrintWriter(bws);
          total = midterm1*0.3 + midterm2*0.3 + finalScore*0.4;
          out.println(sname + " " + total);
        catch (FileNotFoundException ex) {
          System.out.println("File not found: in.dat");
        catch (IOException ex) {
          System.out.println(ex.getMessage());
        finally {
          try {
            if (brs != null) brs.close();
            if (bws != null) bws.close();
          catch (IOException ex) {
            System.out.println(ex);
    }[\code]
    errorsC:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:43: class expected
        midterm1 = double.parseDouble(mid1);
                          ^
    C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:44: class expected
        midterm2 = double.parseDouble(mid2);
                          ^
    C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:45: class expected
        finalScore = double.parseDouble(finalScore);
                            ^
    C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:43: incompatible types
    found   : java.lang.Class
    required: double
        midterm1 = double.parseDouble(mid1);
                         ^
    C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:44: incompatible types
    found   : java.lang.Class
    required: double
        midterm2 = double.parseDouble(mid2);
                         ^
    C:\j2sdk1.4.1_06\bin\ParsingTextFile1.java:45: incompatible types
    found   : java.lang.Class
    required: double
        finalScore = double.parseDouble(finalScore);
                           ^
    6 errors
    Process completed.

    while(line.hasMoreTokens())
    sname = tokenizer.nextToken();  
       mid1 = tokenizer.nextToken();   
      mid2 = tokenizer.nextToken();  
       finalSc= tokenizer.nextToken(); 
        midterm1 = double.parseDouble(mid1)//this code not working
         midterm2 = double.parseDouble(mid2);)//this code not working  
       finalScore = double.parseDouble(finalScore);//this code not working
    }if it doesn't work then you need to add delimiter Or the token that you are trying to convert into is not valid.

  • Enabling Create New Query and Personalize in Check Status

    Hi All,
    We followed below steps Enable Create New Query and Personalize in Check Status
    Go to the role of the user - PFCG - Authorizations - Change authorization data - Cross-application authorization objects - authorizations for Personal Object Work List (POWL) iViews
    Specified the application ID POWL_APPID - SAPSRM_E_CHECKSTATUS
    What should be done to enable define query and personalize for all users.
    We have changed the following settings -
    In activity POWL_CAT - '??' , POWL_LSEL-DISALLOWED - POWL_QUERY - ?? , POWL_RA_AL - ?? , POWL_TABLE - ??.
    With our current settings Create New Query and Personalize in Check Status appear but are disabled (greyed out)
    New Query Button appears but clicking on it produces no output.
    Nikhil
    Edited by: Nikhil Malvankar on Sep 12, 2011 5:57 AM

    You could the following to check if the Query still exists in the database:
    Open SQL Management Studio and connect to the SQL Server hosting the ConfigMgr database
    In SQL Managemnt Studio, Expand Database, Expand CM_YourSiteCode
    Expand tables and find the dbo.Queries table
    Right-click the dbo.Queries table and select Select Top 1000 Rows
    See if you can find your "ghost" Query
    Please note - it IS NOT supported
    to make direct changes to ConfigMgr database so I would properly call PSS on this one before you start getting creative.

  • Trap string output from resultset and pass the value to getSchema.

    I want to get the string ldb output frm the resultset and pass it to getSchemas(ldb).kindly let me know how to do it,right now it is throwing error like variable ldb might not have been initialised.
    public boolean Err_getSchemas() {
    boolean ret = true;
    try {
    System.out.println("**** Testing getSchemas Tests : - ");
    if(login()) {
    Statement stmt = con.createStatement();
    ResultSet rs;
    String ldb;
    rs = stmt.executeQuery("SELECT identifier FROM ldb_catalog");
    while(rs.next())
    ldb = rs.getString(1);
    //String ldb = rs.getString(1);
    //System.out.println("lll"+ldb);
    try{
    System.out.println("1.Testing DatabaseMetaData.getSchemas() with string ldb");
    ordbjava.jdbc.ordbMetaData dbmd = ( ordbjava.jdbc.ordbMetaData)con.getMetaData();
    ResultSet dbmdrst = dbmd.getSchemas(ldb);
    System.out.println(" Exception not thrown: TEST Pass ");
    dbmdrst.close();
    }catch(Exception ex){
    System.out.println("***JDBCMetaData.getSchemas() with string ldb failure***");
                   System.out.println(" Catch Exception"+ex );
    catch (SQLException e) {
    printExceptionStack(e);
    System.out.println("***ordbCollection Preparation Error Caught SQLException: " + e.getMessage());
    return false;
    finally {
    try {
    con.close();
    catch (SQLException e) {}
    return ret;
    }

    I want to get the string ldb output frm the resultset and pass it to getSchemas(ldb).kindly let me know how to do it,right now it is throwing error like variable ldb might not have been initialised.
    public boolean Err_getSchemas() {
    boolean ret = true;
    try {
    System.out.println("**** Testing getSchemas Tests : - ");
    if(login()) {
    Statement stmt = con.createStatement();
    ResultSet rs;
    String ldb;
    rs = stmt.executeQuery("SELECT identifier FROM ldb_catalog");
    while(rs.next())
    ldb = rs.getString(1);
    //String ldb = rs.getString(1);
    //System.out.println("lll"+ldb);
    try{
    System.out.println("1.Testing DatabaseMetaData.getSchemas() with string ldb");
    ordbjava.jdbc.ordbMetaData dbmd = ( ordbjava.jdbc.ordbMetaData)con.getMetaData();
    ResultSet dbmdrst = dbmd.getSchemas(ldb);
    System.out.println(" Exception not thrown: TEST Pass ");
    dbmdrst.close();
    }catch(Exception ex){
    System.out.println("***JDBCMetaData.getSchemas() with string ldb failure***");
                   System.out.println(" Catch Exception"+ex );
    catch (SQLException e) {
    printExceptionStack(e);
    System.out.println("***ordbCollection Preparation Error Caught SQLException: " + e.getMessage());
    return false;
    finally {
    try {
    con.close();
    catch (SQLException e) {}
    return ret;
    }

  • Need help Take out the null values from the ResultSet and Create a XML file

    hi,
    I wrote something which connects to Database and gets the ResultSet. From that ResultSet I am creating
    a XML file. IN my program these are the main two classes Frame1 and ResultSetToXML. ResultSetToXML which
    takes ResultSet & Boolean value in its constructor. I am passing the ResultSet and Boolean value
    from Frame1 class. I am passing the boolean value to get the null values from the ResultSet and then add those
    null values to XML File. When i run the program it works alright and adds the null and not null values to
    the file. But when i pass the boolean value to take out the null values it would not take it out and adds
    the null and not null values.
    Please look at the code i am posing. I am showing step by step where its not adding the null values.
    Any help is always appreciated.
    Thanks in advance.
    ============================================================================
    Frame1 Class
    ============
    public class Frame1 extends JFrame{
    private JPanel contentPane;
    private XQuery xQuery1 = new XQuery();
    private XYLayout xYLayout1 = new XYLayout();
    public Document doc;
    private JButton jButton2 = new JButton();
    private Connection con;
    private Statement stmt;
    private ResultSetToXML rstx;
    //Construct the frame
    public Frame1() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    //Component initialization
    private void jbInit() throws Exception {
    //setIconImage(Toolkit.getDefaultToolkit().createImage(Frame1.class.getResource("[Your Icon]")));
    contentPane = (JPanel) this.getContentPane();
    xQuery1.setSql("");
    xQuery1.setUrl("jdbc:odbc:SCANODBC");
    xQuery1.setUserName("SYSDBA");
    xQuery1.setPassword("masterkey");
    xQuery1.setDriver("sun.jdbc.odbc.JdbcOdbcDriver");
    contentPane.setLayout(xYLayout1);
    this.setSize(new Dimension(400, 300));
    this.setTitle("Frame Title");
    xQuery1.setSql("Select * from Pinfo where pid=2 or pid=4");
    jButton2.setText("Get XML from DB");
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    catch(java.lang.ClassNotFoundException ex) {
    System.err.print("ClassNotFoundException: ");
    System.err.println(ex.getMessage());
    try {
    con = DriverManager.getConnection("jdbc:odbc:SCANODBC","SYSDBA", "masterkey");
    stmt = con.createStatement();
    catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jButton2_actionPerformed(e);
    contentPane.add(jButton2, new XYConstraints(126, 113, -1, -1));
    //Overridden so we can exit when window is closed
    protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
    System.exit(0);
    void jButton2_actionPerformed(ActionEvent e) {
    try{
    OutputStream out;
    XMLOutputter outputter;
    Element root;
    org.jdom.Document doc;
    root = new Element("PINFO");
    String query = "SELECT * FROM PINFO WHERE PID=2 OR PID=4";
    ResultSet rs = stmt.executeQuery(query);
    /*===========This is where i am passing the ResultSet and boolean=======
    ===========value to either add the null or not null values in the file======*/
    rstx = new ResultSetToXML(rs,true);
    } //end of try
    catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    ======================================================================================
    ResultSetToXML class
    ====================
    public class ResultSetToXML {
    private OutputStream out;
    private Element root;
    private XMLOutputter outputter;
    private Document doc;
    // Constructor
    public ResultSetToXML(ResultSet rs, boolean checkifnull){
    try{
    String tagname="";
    String tagvalue="";
    root = new Element("pinfo");
    while (rs.next()){
    Element users = new Element("Record");
    for(int i=1;i<=rs.getMetaData().getColumnCount(); ++i){
    tagname= rs.getMetaData().getColumnName(i);
    tagvalue=rs.getString(i);
    System.out.println(tagname);
    System.out.println(tagvalue);
    /*============if the boolean value is false it adds the null and not
    null value to the file =====================*/
    /*============else it checks if the value is null or the length is
    less than 0 and does the else clause in the if(checkifnull)===*/
    if(checkifnull){ 
    if((tagvalue == null) || tagvalue.length() < 0 ){
    users.addContent((new Element(tagname).setText(tagvalue)));
    else{
    users.addContent((new Element(tagname).setText(tagvalue)));
    else{
    users.addContent((new Element(tagname).setText(tagvalue)));
    root.addContent(users);
    out=new FileOutputStream("c:/XMLFile.xml");
    doc = new Document(root);
    outputter = new XMLOutputter();
    outputter.output(doc,out);
    catch(IOException ioe){
    System.out.println(ioe);
    catch(SQLException sqle){

    Can someone please help me with this problem
    Thanks.

  • Problem with store ResultSet and show result in table

    Hi, I'm kind of new in ADF, I need to store ResultSet and show result in table-component. I have two problems:
    1) I get my ResultSet by calling callStoredProcedure(...) and this returns actually ref_cursor as ResultSet.
    When I try to println() contains of this result set in this method - it works OK (commented part),
    but when I want to println() somewhere else (eg. in retrieveRefCursor() method) it doesn't work.
    The problem is that the scrollability of the ResultSet is lost - it becomes a TYPE_FORWARD_ONLY ResultSet.
    Is there any way to store data from ref_cursor for a long time?
    2) My second problem is "store any result set and show this data in table". I have tried use method storeNewResultSet() but
    without result (table contains only "No rows yet" and everything seems to be OK - no exception, no warning, no error...).
    I have tried to call this method with ResultSet from select on dbs (without resultSet as ref_cursor ) - no result with createRowFromResultSet(),
    storeNewResultSet(), setUserDataForCollection()...
    I've tried a lot of ways to do this, but it doesn't work. I really don't know how to make it so it can work.
    Thanks for your help.
    ADF BC, JDev 11.1.1.0
    This is my code from ViewObjectImpl
    package tp.model ;
    import com.sun.jmx.mbeanserver.MetaData ;
    import java.sql.CallableStatement ;
    import java.sql.Connection ;
    import java.sql.PreparedStatement ;
    import java.sql.ResultSet ;
    import java.sql.ResultSetMetaData ;
    import java.sql.SQLException ;
    import java.sql.Statement ;
    import java.sql.Types ;
    import oracle.jbo.JboException ;
    import oracle.jbo.server.SQLBuilder ;
    import oracle.jbo.server.ViewObjectImpl ;
    import oracle.jbo.server.ViewRowImpl ;
    import oracle.jbo.server.ViewRowSetImpl ;
    import oracle.jdbc.OracleCallableStatement ;
    import oracle.jdbc.OracleConnection ;
    import oracle.jdbc.OracleTypes ;
    public class Profiles1ViewImpl extends ViewObjectImpl {
        private static final String SQL_STM = "begin Pkg_profile.get_profile_list(?,?,?,?);end;" ;
        public Profiles1ViewImpl () {
        /* 0. */
        protected void create () {
            getViewDef ().setQuery ( null ) ;
            getViewDef ().setSelectClause ( null ) ;
            setQuery ( null ) ;
        public Connection getCurrentConnection () throws SQLException {
            // Note that we never execute this statement, so no commit really happens
            Connection conn = null ;
            PreparedStatement st = getDBTransaction ().createPreparedStatement ( "commit" , 1 ) ;
            conn = st.getConnection () ;
            st.close () ;
            return conn ;
        /* 1. */
        protected void executeQueryForCollection ( Object qc , Object[] params , int numUserParams ) {
            storeNewResultSet ( qc , retrieveRefCursor ( qc , params ) ) ;
            // callStoredProcedure ( qc , SQL_STM ) ;
            super.executeQueryForCollection ( qc , params , numUserParams ) ;
        /* 2. */
        private ResultSet retrieveRefCursor ( Object qc , Object[] params ) {
            ResultSet rs = null ;
            rs = callStoredProcedure ( qc , SQL_STM ) ;
            return rs ;
        /* 3. */
        public ResultSet callStoredProcedure ( Object qc , String stmt ) {
            CallableStatement st = null ;
            ResultSet refCurResultSet = null ;
            try {
                st = getDBTransaction ().createCallableStatement ( stmt , 0 ) ; // call 
                st.setObject ( 1 , 571 ) ; //set id of my record to 571
                st.registerOutParameter ( 2 , OracleTypes.CURSOR ) ; // my ref_cursor
                st.registerOutParameter ( 3 , Types.NUMERIC ) ;
                st.registerOutParameter ( 4 , Types.VARCHAR ) ;
                st.execute () ; //executeUpdate
                System.out.println ( "Numeric " + st.getObject ( 3 ) ) ;
                System.out.println ( "Varchar " + st.getObject ( 4 ) ) ;
                refCurResultSet = ( ResultSet ) st.getObject ( 2 ) ; //set Cursoru to ResultSet
                //   setUserDataForCollection(qc, refCurResultSet); //don't work
                //   createRowFromResultSet ( qc , refCurResultSet ) ; //don't work
                /* this works but only one-time call - so my resultSet(cursor) really have a data
                while ( refCurResultSet.next () ) {
                    String nameProfile = refCurResultSet.getString ( 2 ) ;
                    System.out.println ( "Name profile: " + nameProfile ) ;
                return refCurResultSet ;
            } catch ( SQLException e ) {
                System.out.println ( "sql ex " + e ) ;
                throw new JboException ( e ) ;
            } finally {
                if ( st != null ) {
                    try {
                        st.close () ; // 7. Close the statement
                    } catch ( SQLException e ) {
                        System.out.println ( "sql exx2 " + e ) ;
        /* 4. Store a new result set in the query-collection-private user-data context */
        private void storeNewResultSet ( Object qc , ResultSet rs ) {
            ResultSet existingRs = getResultSet ( qc ) ;
            // If this query collection is getting reused, close out any previous rowset
            if ( existingRs != null ) {
                try {
                   existingRs.close () ;
                } catch ( SQLException s ) {
                    System.out.println ( "sql err " + s ) ;
            setUserDataForCollection ( qc , rs ) ; //should store my result set
            hasNextForCollection ( qc ) ; // Prime the pump with the first row.
        /*  5. Retrieve the result set wrapper from the query-collection user-data      */
        private ResultSet getResultSet ( Object qc ) {
            return ( ResultSet ) getUserDataForCollection ( qc ) ;
        // createRowFromResultSet - overridden for custom java data source support - also doesn't work
       protected ViewRowImpl createRowFromResultSet ( Object qc , ResultSet resultSet ) {
            ViewRowImpl value = super.createRowFromResultSet ( qc , resultSet ) ;
            return value ;
    }

    Hi I have the same problem like you ...
    My SQL Definition:
    CREATE OR REPLACE TYPE RMSPRD.NB_TAB_STOREDATA is table of NB_STOREDATA_REC
    CREATE OR REPLACE TYPE RMSPRD.NB_STOREDATA_REC AS OBJECT (
       v_title            VARCHAR2(100),
       v_store            VARCHAR2(50),
       v_sales            NUMBER(20,4),
       v_cost             NUMBER(20,4),
       v_units            NUMBER(12,4),
       v_margin           NUMBER(6,2),
       v_ly_sales         NUMBER(20,4),
       v_ly_cost          NUMBER(20,4),
       v_ly_units         NUMBER(12,4),
       v_ly_margin        NUMBER(6,2),
       v_sales_variance   NUMBER(6,2)
    CREATE OR REPLACE PACKAGE RMSPRD.NB_SALES_DATA
    AS
    v_sales_format_tab   nb_tab_storedata;
    FUNCTION sales_data_by_format_gen (
          key_value         IN       VARCHAR2,
          l_to_date         IN       DATE DEFAULT SYSDATE-1,
          l_from_date       IN       DATE DEFAULT TRUNC (SYSDATE, 'YYYY')
          RETURN nb_tab_storedata;
    I have a PLSQL function .. that will return table ..
    when i use this in sql developer it is working fine....
    select * from table (NB_SALES_DATA.sales_data_by_format_gen('TSC',
                                        '05-Aug-2012',
                                        '01-Aug-2012') )
    it returning table format record.
    I am not able to call from VO object. ...
    Hope you can help me .. please tell me step by step process...
    protected Object callStoredFunction(int sqlReturnType, String stmt,
    Object[] bindVars) {
    System.out.println("--> 1");
    CallableStatement st = null;
    try {
    st = getDBTransaction().createCallableStatement("begin ? := " +"NB_SALES_DATA.sales_data_by_format_gen('TSC','05-Aug-2012','01-Aug-2012') ; end;", 0);
    System.out.println("--> 2");
    st.executeUpdate();
    System.out.println("--> 3");
    return st.getObject(1);
    catch (SQLException e) {
    e.printStackTrace();
    throw new JboException(e);

  • JDBC-ResultSet and ArrayList

    Hi guys,
    I need a help. The situation is next: I�m trying to store some results of ResultSet into ArrayList. Unfortunately, when I�m retrieving the data from ArrayList, the result, which I�m getting, is only the last row of a table. The result is repeating as many times as ArrayList size is. Could somebody explain me why it happens?
    There is a snippet of the code to get a data from the ResultSet and add it into ArrayList:
    // Execute a query
    String sql = "select * from user";
              Statement stmt = conn.createStatement();
              ResultSet rs = stmt.executeQuery(sql);
              ArrayList list = new ArrayList();
              // Extract data from the result set
              while(rs.next()) {
    CustomerBean cb = new CustomerBean();
                   if(rs.getString("first_name")!=null)cb.setFirstName(rs.getString("first_name"));
                   if(rs.getString("last_name")!=null)cb.setLastName(rs.getString("last_name"));
                   if(rs.getDate("dob")!=null)cb.setDob(rs.getDate("dob"));
                   list.add(cb);
    Another snippet of the code to retrieve the data from ArrayList:
    for (int i = 0; i < cb.getUserData().size(); i++){
    System.out.println("First -"+((CustomerBean)cb.getUserData().get(i)).getFirstName()); // hire an error
    System.out.println("Last - "+((CustomerBean) cb.getUserData().get(i)).getLastName());// hire an error
    System.out.println("Dob - "+((CustomerBean) cb.getUserData().get(i)).getDob());// hire an error
    Thank you in advance

    One thing you should change is the multiple calls on the same column to retrieve the columns value from your results set. This can definately be problematic depending on the JDBC driver you're using.
    I might suggest something like this:
    // Execute a query
    String sql = "select * from user";
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(sql);
    ArrayList list = new ArrayList();
    // Extract data from the result set
    while(rs.next()) {
    CustomerBean cb = new CustomerBean();
    String firstName = rs.getString( "first_name" );
    String lastName = rs.getString( "first_name" );
    Date dateOfBirth = rs.getDate( "dob" );
    if ( firstName != null )
       cb.setFirstName( firstName );
    if ( lastName != null )
       cb.setLastName( lastName );
    if ( dateOfBirth != null )
       cb.setDob( dateOfBirth );
    list.add( sb );
    for (int i = 0; i < list.size(); i++){
    System.out.println("First -"+((CustomerBean)list.get(i)).getFirstName()); // hire an error
    System.out.println("Last - "+((CustomerBean)list.get(i)).getLastName());// hire an error
    System.out.println("Dob - "+((CustomerBean)list.get(i)).getDob());// hire an error
    }Although this might not immediately solve your problem, it might help narrow down the area where the problem might exist.

  • Problems with string tokenizer

    okay heres my problem, i have a textarea displaying a program listing and i have to extract variables i.e public int something;
    i have tried many different approaches but still the output is not what i was looking for. Can someone have a look at my code and check for mistakes that i cant find
    public void createDataDictionary() {
              if(fullText.equals("")) return;//do nothing if no text exists
              String checkText = fileContents.getText();//store text area contents into string
              String dataType = "";
              String variable = "";
              String accessModifier = "";
              StringTokenizer str = new StringTokenizer(checkText," \n", true);
              fileCheckBox.setText("");//clear file check box
              while(str.hasMoreTokens()) {//loop while there are more tokens to tokenize
                   try{                    
                        checkText = str.nextToken();
                        //check for comments
                        if((checkText.startsWith("//")) || (checkText.equals("//")) ||
                           (checkText.startsWith("/**")) || (checkText.equals("/**")) ||
                           (checkText.startsWith("*")) || (checkText.equals("*"))) {
                             isComment = true;                    
                        if((checkText.equals("\n"))) isComment = false;
                        if(!isComment)
                             //check for access modifiers
                             if((checkText.equals("public")) || (checkText.equals("private")) ||
                                (checkText.equals("protected"))) {
                                          accessModifier = checkText;
                                     }else {
                                          accessModifier = "";
                             //check for data types             
                             if((checkText.equals("boolean")) || (checkText.equals("char")) ||
                                     (checkText.startsWith("String")) || (checkText.equals("int"))) {
                                       dataType = checkText;
                                       variable = str.nextToken();//get variable expression
                                       System.out.println(accessModifier + " " + dataType + " " + variable);
                   }catch(NoSuchElementException nsee) {//not enough tokens to complete operation
                        JOptionPane.showMessageDialog(null, "End of file");
                        return;//break from method
         }here is sample text
    private String seven = "help";
    char five[];
    // String here
    //int found
    public boolean okay
    and here is the output
    String
    char
    String
    boolean
    //note the space before each output
    hope someone can help
    thanx in advance

    1. Why do you check to see if the token starts with
    //, /*, etc, etc. Later you check if the token
    equals private, public, protected. It couldn't
    equal if it started with a comment.if the token starts with a comment i dont want to read the rest of the line, so i set the isComment flag to true
    2. I strongly suggest that you do it line by line.
    Perhaps a string tokenizer that only tokenizes by
    lines, then within that loop, another that tokenizes
    by whitespace. i take it you mean putting the text into a bufferedreader and then using readLine()?? Bit new to string tokenization as you can possibly see
    i managed to get the small test text to work more or less as i wanted but when ever i load a large code listing, the results are erratic to say the least
    heres a section of this code
    private int textNum = 0;/**Integer used to hold the text position within any given line*/
         private int lineNum = 0;/**Integer used to hold the line number within any given file*/
         static boolean application = false;/**Used to track if applet is ran from a browser or JAR file*/
         static boolean fileOpened = false;/**Used to track if file has already been opened*/
         static boolean isComment = false;
         private char lCurve = '(';
         private char rCurve = ')';
         private char lCurly = '{';
         private char rCurly = '}';
         private char lSquare = '[';
         private char rSquare = ']';
         String fullText = "";and heres the output
    public int textNum //should be private!!!!
    int lineNum //missing private
    boolean application //missing static
    boolean fileOpened //missing static
    boolean isComment //missing static
    //all below missing private     
    char lCurve
    char rCurve
    char lCurly
    char rCurly
    char lSquare
    char rSquare
    String fullText //not there at all

  • Implicit vs explicit close of resultsets and statements?

    Hi friends.I am a newbie Java Developer..Okay Here goes
    I have just made a LAN based Java application using Swing,JDBC with backend as MS-Access..The backend is on a shared network drive..
    The application is distributed as jar files on the LAN PCs..
    Everywhere I have connected to the database I have just closed the connection explicitly like this
    con.close();
    I do not close the associated resultset and statement explicitly
    The specification says associated statements and resultsets close when you close
    the connection,even if you don't explicitly close them
    Also I am not using connection pool..its simple basic connection using DriverManager
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String url = "jdbcdbcSN name";
    String user = "";
    String pw = "";
    con = DriverManager.getConnection(url, user, pw);
    Statement stmt = con.createStatement();
    String select = "" ;
    ResultSet rows = stmt.executeQuery(select);
    On the net everyone says to explicitly close everything..but I did not know that
    earlier..
    If specification says everything closes on
    closing connection why do ppl insist on closing everything explicitly..?
    Or is this driver dependent..don't the drivers go through the specification..
    My driver is the Sun JDBC ODBC bridge.....
    I found this method DriverManager.setLogwriter()
    It prints out a trace of all JDBC operations..
    So I ran a sample program with this method included...
    I redirected output to a log file..
    In that program I just explicitly close the connection without closing the
    statements and resultsets explicitly...
    After running the program and seeing the log I saw that the statements
    and resultsets are closed implicitly If I just close the connection explicitly..
    I am putting the log file and the code..
    Have a look at the end of the log file..
    Code
    import java.sql.;
    import java.io.;
    class gc4test
    public static void main(String args[])
    Connection con = null;
    try
    FileWriter fwTrace = new FileWriter("c:\\log.txt");
    PrintWriter pwTrace= new PrintWriter(fwTrace);
    DriverManager.setLogWriter(pwTrace);
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String url = "jdbc:odbc:pravahcon";
    String user = "admin";
    String pw = "ash123";
    con = DriverManager.getConnection(url, user, pw);
    Statement stmt = con.createStatement();
    Statement stmt1 = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
    Statement stmt2 = con.createStatement();
    Statement stmt3 = con.createStatement();
    Statement stmt4 = con.createStatement();
    Statement stmt5 = con.createStatement();
    Statement stmt6 = con.createStatement();
    Statement stmt7 = con.createStatement();
    String select = "SELECT * FROM Users" ;
    ResultSet rows = stmt.executeQuery(select);
    ResultSet rows1 = stmt1.executeQuery(select);
    while(rows.next())
    con.close();
    catch (ClassNotFoundException f)
    System.out.println(f.getMessage());
    System.exit(0);
    catch (SQLException g)
    System.out.println(g.getMessage());
    System.exit(0);
    catch (Exception e)
    System.out.println(e.getMessage());
    System.exit(0);
    End of Log File
    Setting statement option (SQLSetStmtAttr), hStmt=50275112, fOption=25
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    Fetching (SQLFetch), hStmt=50274224
    End of result set (SQL_NO_DATA)
    *Connection.close
    8 Statement(s) to close
    *Statement.close
    Free statement (SQLFreeStmt), hStmt=50281544, fOption=1
    deregistering Statement sun.jdbc.odbc.JdbcOdbcStatement@2e7263
    *Statement.close
    Free statement (SQLFreeStmt), hStmt=50277224, fOption=1
    deregistering Statement sun.jdbc.odbc.JdbcOdbcStatement@1bf216a
    *Statement.close
    *ResultSet.close
    *ResultSet has been closed
    Free statement (SQLFreeStmt), hStmt=50274224, fOption=1
    deregistering Statement sun.jdbc.odbc.JdbcOdbcStatement@156ee8e
    *Statement.close
    Free statement (SQLFreeStmt), hStmt=50280464, fOption=1
    deregistering Statement sun.jdbc.odbc.JdbcOdbcStatement@c20e24
    *Statement.close
    Free statement (SQLFreeStmt), hStmt=50278304, fOption=1
    deregistering Statement sun.jdbc.odbc.JdbcOdbcStatement@12ac982
    *Statement.close
    *ResultSet.close
    *ResultSet has been closed
    Free statement (SQLFreeStmt), hStmt=50275112, fOption=1
    deregistering Statement sun.jdbc.odbc.JdbcOdbcStatement@e0e1c6
    *Statement.close
    Free statement (SQLFreeStmt), hStmt=50276144, fOption=1
    deregistering Statement sun.jdbc.odbc.JdbcOdbcStatement@6ca1c
    *Statement.close
    Free statement (SQLFreeStmt), hStmt=50279384, fOption=1
    deregistering Statement sun.jdbc.odbc.JdbcOdbcStatement@1389e4
    Disconnecting (SQLDisconnect), hDbc=50271048
    Closing connection (SQLFreeConnect), hDbc=50271048
    Closing environment (SQLFreeEnv), hEnv=50270880
    So like what these implicitly closed statements and resultsets are different from explicitly closed
    resultsets and statements..?

    Please do not crosspost/doublepost the same question again. It is rude in terms of netiquette.
    Stick to one topic: [http://forums.sun.com/thread.jspa?threadID=5393387&messageID=10745794#10745794].

  • How to retrieve IndividualStrings from a txt file using String Tokenizer.

    hello can any one help me to retrieve the individual strings from a txt file using string tokenizer or some thing like that.
    the data in my txt file looks like this way.
    Data1;
    abc; cder; efu; frg;
    abc1; cder2; efu3; frg4;
    Data2
    sdfabc; sdfcder; hvhefu; fgfrg;
    uhfhabc; gffjcder; yugefu; hhfufrg;
    Data3
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    i need to read the data as an individual strings and i need to pass those values to diffarent labels,the dat in Data3 i have to read those values and add to an table datamodel as 6 columns and rows depends on the data.
    i try to retrieve data using buffered reader and inputstream reader,but only the way i am retrieving data as an big string of entire line ,i tried with stringtokenizer but some how i was failed to retrive the data in a way i want,any help would be appreciated.
    Regards,

    Hmmm... looks like the file format isn't even very consistent... why the semicolon after Data1 but not after Data2 or Data3??
    Your algorithm is reading character-by-character, and most of the time it's easier to let a StringTokenizer or StreamTokenizer do the work of lexical analysis and let you focus on the parsing.
    I am also going to assume your format is very rigid. E.g. section Data1 will ALWAYS come before section Data2, which will come before section Data3, etc... and you might even make the assumption there can never be a Data4, 5, 6, etc... (this is why its nice to have some exact specification, like a grammar, so you know exactly what is and is not allowed.) I will also assume that the section names will always be the same, namely "DataX" where X is a decimal digit.
    I tend to like to use StreamTokenizer for this sort of thing, but the additional power and flexibility it gives comes at the price of a steeper learning curve (and it's a little buggy too). So I will ignore this class and focus on StringTokenizer.
    I would suggest something like this general framework:
    //make a BufferedReader up here...
    do
      String line = myBufferedReader.readLine();
      if (line!=null && line.trim().length()>0)
        line = line.trim();
        //do some processing on the line
    while (line!=null);So what processing to do inside the if statement?
    Well, you can recognize the DataX lines easily enough - just do something like a line.startsWith("Data") and check that the last char is a digit... you can even ignore the digit if you know the sections come in a certain order (simplifying assumptions can simplify the code).
    Once you figure out which section you're in, you can parse the succeeding lines appropriately. You might instantiate a StringTokenizer, i.e. StringTokenizer strtok = new StringTokenizer(line, ";, "); and then read out the tokens into some Collection, based on the section #. E.g.
    strtok = new StringTokenizer(line, ";, ");
    if (sectionNo==0)
      //read the tokens into the Labels1 collection
    else if (sectionNo==1)
      //read the tokens into the Labels2 collection
    else //sectionNo must be 2
      //create a new line in your table model and populate it with the token values...
    }I don't think the delimiters are necessary if you are using end-of-line's as delimiters (which is implicit in the fact that you are reading the text out line-by-line). So the original file format you listed looks fine (except you might want to get rid of that rogue semicolon).
    Good luck.

  • Help!! i dont know how to make use of token from string tokenizer :(

    Hi,
    I would like to ask how to manipulate the token that are taken from string tokenizer. For example :
    input = a b 1 f 986
    supposed output:
    a
    b
    1
    f
    986
    How to make the output look like this?
    Output = (a,b,f),(1,986)
    Below is the source code of Algebra.java
    import java.io.*;
    import java.util.*;
    * Read and print, using BufferedReader from System.in, onto System.out
    public class Algebra {
    public static void main(String[] av) {
    try {
    BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
    String inputLine;
    System.out.print("Input =");
    while ((inputLine = is.readLine()) != null) {
    System.out.println("Output="+inputLine);
    StringTokenizer st =
    new StringTokenizer(inputLine, ", |");
    while (st.hasMoreElements())
    System.out.println("Token: " + st.nextElement());
    break;
    is.close();
    } catch (IOException e) {
    System.out.println("IOException: " + e);
    Thank You

    You can modify this to serve your goal.
    BufferedReader is=null;
    try {
    is = new BufferedReader(new InputStreamReader(new FileInputStream("Data.txt")));
    StreamTokenizer st = new StreamTokenizer(is);
    int n=0,k=0,q=0;
    String[] s=new String[20];
    String[] s0=new String[10];
    while(st.nextToken() != StreamTokenizer.TT_EOF) {
            switch(st.ttype) {
              case StreamTokenizer.TT_EOL:
                s[k] = new String("EOL");k++;
                break;
              case StreamTokenizer.TT_NUMBER:
                s0[q] = Double.toString(st.nval);q++;
                break;
              case StreamTokenizer.TT_WORD:
                s[k] = st.sval; // Already a String
                 k++;
                break;
              default: // single character in ttype
                s[k] = String.valueOf((char)st.ttype); k++;
            }  //end of while
       //   Some output processing here
    }catch(IOException ioe){
       ioe.printStackTrace();
    }catch(ArrayIndexOutOfBoundsException bx){
       System.err.println(bx);
    }finally{
           try{      if(is !=null)     is.close();}catch(IOException ioe){;}
    }

  • String Tokenizer/ Multiple Client app.

    Hi all,
    I am developing a multi user pure Java App.
    My situation:
    1. client request server for connection. > server accepted
    2. client send his details (name*|*group*|*ID)
    3. server receive the string, update itself and other client accordingly
    My problem:
    1. to send client detail (name*|*group*|*ID), String tokenizer is being used? and *|" serve as delimeter ?
    2. how do create an statement that count the total user connected to server or leave the server
    3. and how to assign an identifier to each connected client, thus server can perform differ operation based on the identifier.
    Thanks Ya, if someone can provide me some suggestions
    Happy Life

    To answer your problems directly
    1. Client Info: Yes, read all information from the client using an inputstream. convert that into a String, and use StringTokenizer (str, "|") to parse the information
    2. # of clients: After a client has connected to your server, they will be automatically shunted to another port that that user alone communicates on. You should set up a new thread to listen to data being sent on that port. Keep these listeners in an array/vector/arraylist and use getSize()
    3. The identifier could just be their port #

  • String tokenizer manipulation

    Hi,
    I would like to ask how to manipulate the token that are taken from string tokenizer. For example :
    input = a b 1 f 986
    supposed output:
    a
    b
    1
    f
    986
    How to make the output look like this?
    Output = (a,b,f),(1,986)
    How to make the program will be able to recognize and arrange the data into the output that i want.
    Below is the source code of Algebra.java
    import java.io.*;
    import java.util.*;
    * Read and print, using BufferedReader from System.in, onto System.out
    public class Algebra {
    public static void main(String[] av) {
    try {
    BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
    String inputLine;
    System.out.print("Input =");
    while ((inputLine = is.readLine()) != null) {
    System.out.println("Output="+inputLine);
    StringTokenizer st =
    new StringTokenizer(inputLine, ", |");
    while (st.hasMoreElements())
    System.out.println("Token: " + st.nextElement());
    break;
    is.close();
    } catch (IOException e) {
    System.out.println("IOException: " + e);
    Thank You

    I'd make two arrays and fill them separately depending on whether you can parse the token as an int or not. Try running this code:
    import java.io.*;
    import java.util.*;
    * Read and print, using BufferedReader from System.in, onto System.out
    public class Main {
    public static void main(String[] av) {
        int numbers[] = new int[20];
        String variables[] = new String[20];
        int numberPosition = 0;
        int variablePosition = 0;
        try {
            BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
            String inputLine;
            System.out.print("Input =");
            while ((inputLine = is.readLine()) != null) {
                StringTokenizer st =
                new StringTokenizer(inputLine, ", |");
                while (st.hasMoreElements()) {
                    String token = st.nextToken();
                    try {
                        int i = Integer.parseInt(token);
                        numbers[numberPosition++] = i;
                    } catch (NumberFormatException e) {
                        variables[variablePosition++] = token;
                System.out.print("(");
                for (int x = 0; x < variablePosition -1; x++)
                    System.out.print(variables[x]+",");
                System.out.print(variables[variablePosition-1]+")");  
                System.out.print("(");
                for (int x = 0; x < numberPosition -1; x++)
                    System.out.print(numbers[x]+",");
                System.out.print(numbers[numberPosition-1]+")");           
                break;
        } catch (IOException e) {
            System.out.println("IOException: " + e);
    }Sample Output:
    Input =a b 1 f 986
    (a,b,f)(1,986)
    press any key to exit...

  • In your lab05, replace instructor's Tokenizer class and MyStackQueue packag

    Objective:
    The objective of this lab is to get you some experience in processing strings character by
    character and in implementing stacks and queues in a class package.
    The programming assignment:
    In your lab05, replace instructor’s Tokenizer class and MyStackQueue package with your own.
    Requirements:
    1. You must use an array to implement your queue.
    2. You must use a linked list to implement your stack.
    3. You must use the following frame work to implement your tokenizer.
    class Tokenizer {
    private char [] Buf;
    private int cur;
    Tokenizer(String infixExpression) {
    Buf = infixExpression.toCharArray();
    cur = 0;
    Token nextToken() {
    1. Skip blanks.
    2. if (cur>=Buf.length) return null;
    3. If the next character is a digit, keep reading until a non-digit is read.
    Convert the string of digits into an integer.
    String Digits = new String(Buf, start, len);
    int num = Integer.valueOf(Digits).intValue();
    Create and return an operand.
    4. Otherwise, use the next character to create and return an operator.
    class Tokenizer {
         private char[] Buf;
         private int cur;
         Tokenizer(String infixExpression) {
              Buf = infixExpression.toCharArray();
              cur = 0;
         Token nextToken() {
              int bufLength = Buf.length;
              Object obj = null;
              // ignore blank space
              while (cur < bufLength && Buf[cur] == ' ') {
                   cur++;
              // if given string having only space return null
              if (cur >= Buf.length)
                   return null;
              StringBuilder value = new StringBuilder();
              // Iterate through each element of string array and construct an string
              // for consecutive digits
              while (cur < bufLength && Buf[cur] <= '9' && Buf[cur] >= '0') {
                   value.append(Buf[cur]);
                   cur++;
              // if digits are there convert all digits as an integer value and create
              // operand
              if (value.length() > 0) {
                   obj = new Operand(Integer.parseInt(value.toString()));
              // if at cur position no digit is present then create operand with the
              // same non digit value
              else {
                   obj = new Operator(Buf[cur]);
                   cur++;
              return ((Token) (obj));
    package StackAndQueue;
    public class Queue {
         private int front;
         private int rear;
         private int capacity;
         private Object S[];
         public Queue() {
              front = 0;
              rear = -1;
              capacity = 100;
              S = new Object[capacity];
         public boolean isEmpty() {
              return S[front] == null;
         public void enqueue(Object obj) {
              int insertionPoint = (rear + 1) % capacity;
              if (S[insertionPoint] == null) {
                   S[insertionPoint] = obj;
                   rear = insertionPoint;
              } else {
                   System.out.println("Queue capacity is full");
         public Object dequeue() {
              if (S[front] != null) {
                   Object obj = S[front];
                   S[front] = null;
                   front = (front + 1) % capacity;
                   return obj;
              } else {
                   System.out.println("Queue is empty");
                   return null;
         public String toString() {
              StringBuilder state = new StringBuilder("[");
              for (int i = front; i < capacity; i++) {
                   if (S[i] != null) {
                        state.append(S[i] + ", ");
              for (int i = 0; i < front; i++) {
                   if (S[i] != null) {
                        state.append(S[i] + ", ");
              if (state.length() > 1) {
                   state.delete(state.length() - 2, state.length() - 1);
              state.append("]");
              return state.toString();
    package StackAndQueue;
    import java.util.LinkedList;
    import java.util.List;
    public class Stack {
         List<Object> linkedList = null;
         public Stack() {
              linkedList = new LinkedList<Object>();
         public boolean isEmpty() {
              return linkedList.size() == 0;
         public void push(Object obj) {
              linkedList.add(obj);
         public Object pop() {
              int topIndex = linkedList.size() - 1;
              if (topIndex >= 0) {
                   Object obj = linkedList.get(topIndex);
                   linkedList.remove(topIndex);
                   return obj;
              } else {
                   return null;
         public Object top() {
              int topIndex = linkedList.size() - 1;
              if (topIndex >= 0) {
                   return linkedList.get(topIndex);
              } else {
                   return null;
    }

    So you want us to do what ?
    Edited by: sabre150 on Oct 9, 2012 3:17 PM
    Cross posted to http://www.coderanch.com/t/594750/Servlets/java/your-lab-replace-instructor-Tokenizer .

Maybe you are looking for