Populating JSF ListBox from DataBase

Hi,
im new to JSF and i have a problem populating Listboxes with database values.
i have 3 listboxes and the 3 are populated from tables in my database.
I would like to filter the returned(from database) values in the 2nd listbox depending on the value selected in the 1st listox.
I dont know how to do this.
BTW i'm usis Ibatis Abator to map the database.
tnx

Here is what I think you are wanting to do:
1. Have the list box show values from a database table.
2. Have the user make selections. Should the user return to that page later in the session, have the previous selection still selected.
Normally, you would bind the listbox to the database table, as is shown in http://developers.sun.com/prodtech/javatools/jscreator/learning/tutorials/2/databoundcomponents.html. The only reason I can think of for not binding directly to the database table is if there is a possiblity that the database table can change (additions, updates, deletes) during the user's session.
Are you able to emulate the above tutorial using the Postgress database? It might be good to pinpoint whether the problem is with the Postgress driver or with the code you are writing.
By the way, if you use a data provider to access the database, as shown in the tutorial, here is how you iterate through the data
        try {
            myDataProvider.cursorFirst();
            do {
                [build your options list here]
            } while (myDataProvider.cursorNext());
        } catch (Exception ex) {
            error("put your message here" +
                    ex.getMessage());
            log("put your message here: " +
                    ex.getMessage(), ex);
        }You are correct to bind the selected property to a session bean property in order to perserve the user selecitons through the user's s session.

Similar Messages

  • Problem in populating jtable data from database

    hi,
    i am using JTable to retrieve data from database and show it in table. JTable
    is working fine with static data. but while retrieving from databse its giving a NullPointerException at getColumnClass() method. Below is complete source code. plzz help.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.sql.*;
    import javax.swing.table.*;
    /*jdbc connection class*/
    class connect
    Connection con;
    Statement stat;
    public connect()throws Exception
    Class.forName("org.postgresql.Driver");
    con=DriverManager.getConnection("jdbc:postgresql://localhost/dl","dl","dl");
    stat=con.createStatement();
    public ResultSet rsf(String rsstr)throws Exception
    ResultSet rs=stat.executeQuery(rsstr);
    return rs;
    public void upf(String upstr)throws Exception
    stat.executeUpdate(upstr);
    class MyTableModel extends AbstractTableModel
    private String[] columnNames = {"name","id","dep","cat","rem","chkout"};
    Object[][] data;
    public MyTableModel()
    try{
    connect conn=new connect();
    ResultSet rs3=conn.rsf("select * from usertab");
    ResultSetMetaData rsmd=rs3.getMetaData();
    int col=rsmd.getColumnCount();
    int cou=0;while(rs3.next()){cou++;}
    data=new Object[cou][col];
    System.out.println(cou+" "+col);
    ResultSet rs2=conn.rsf("select * from usertab");
    int i=0;int j=0;
    for(i=0;i<cou;i++)
    rs2.next();
    for(j=0;j<col;j++)
    data[i][j]=rs2.getString(getColumnName(j));
    System.out.println(data[0][2]);
    }catch(Exception e){System.out.println("DFD "+e);}
            public int getColumnCount() {
                return columnNames.length;
            public int getRowCount() {
                return data.length;
            public String getColumnName(int col) {
                return columnNames[col];
            public Object getValueAt(int row, int col) {
                return data[row][col];
           public Class getColumnClass(int c) {
              return getValueAt(0, c).getClass();
            public boolean isCellEditable(int row, int col) {
                if (col < 2) {
                    return false;
                } else {
                    return true;
            public void setValueAt(Object value, int row, int col) {
                data[row][col] = value;
                fireTableCellUpdated(row, col);
    class MyFrame extends JFrame
    public MyFrame()
         setSize(600,500);
         JPanel p1=new JPanel();
         p1.setBackground(new Color(198,232,189));
         JTable table = new JTable(new MyTableModel());
         table.setPreferredScrollableViewportSize(new Dimension(500,200));
         table.setBackground(new Color(198,232,189));
         JScrollPane scrollPane = new JScrollPane(table);
         scrollPane.setBackground(new Color(198,232,189));
         p1.add(scrollPane);
         getContentPane().add(p1);
    /*Main Class*/
    class test2
         public static void main(String args[])
         MyFrame fr =new MyFrame();
         fr.setVisible(true);
    }thanx

    hi nickelb,
    i had returned Object.class in the getColumnClass() method. But then i
    got NullPointerException at getRowCount() method. i could understand that the
    main problem is in data[][] object. In all the methods its returning null values as it is so declared outside the construtor. But if i declare the object inside the constructor, then the methods could not recognize the object. it seems i cant do the either ways. hope u understood the problem.
    thanx

  • Populating 2dimentional array from database table

    Hi,
    I have created two dimentional array
    TYPE type_DIR IS TABLE OF site_direction.site_direction_id%TYPE INDEX BY    BINARY_INTEGER;
    TYPE type_DIR_LAN IS TABLE OF type_DIR INDEX BY BINARY_INTEGER;
    var_DIR_LAN type_DIR_LAN;I have to populate data into this from a relational database tables "site_direction" and "site_lanes".
    I'm using cursors like below.
      CURSOR lane_numbers(c_site_id NUMBER, c_direction_id NUMBER) IS
           SELECT site_lane_id
          FROM site_lanes
             JOIN report_parameters
               ON site_lane_id = report_parameter_value
            WHERE site_lanes.site_id           = c_site_id
              AND site_lanes.site_direction_id = c_direction_id
              AND report_parameters.report_parameter_id  = in_report_parameter_id
              AND report_parameters.report_parameter_group = 'LANE'
           AND report_parameters.report_parameter_name  = 'LANE'
      ORDER BY site_lane_id;
         CURSOR direction_id(c_site_id NUMBER) IS
         SELECT site_direction_id
           FROM site_direction
           JOIN sites
             ON site_direction.site_id = c_site_id
           JOIN report_parameters
             ON site_direction.site_id = report_parameter_value
          WHERE report_parameters.report_parameter_id  = in_report_parameter_id
               AND report_parameters.report_parameter_group = 'SITE'
            AND report_parameters.report_parameter_name  = 'SITE_ID'
       ORDER BY site_direction_id;  How could I do that?
    Once I got populated two dimentional array with value, how could I return that values?
    Do I need one more 2 dimentional array to return or could I use sys_refcursor?
    Thanks.

    Return the values to what? Using what version of what software?
    Ideally you are using those cursors, though I can't imagine why they are necessary, to BULK COLLECT into the array. If so then just pass the array as a parameter.
    If passing back to an external program like JAVA or .NET then a REF CURSOR would be appropriate.

  • Populating Web List from database Based on Selected Field

    Hi,
    I'm really new to this so pardon my ignorance on the following.
    At my company, we have developed a web site using Oracle
    Application Server using PL*SQL cartridge, i.e. all the
    rendering of forms and processing of data are done using PL*Sql
    commands.
    I have a list field where I'd like the values populated from the
    database using a value specified by a user in another field.
    Example:
    State ____ City ____________________
    When user selects a state, I'd like to be able to dynamically
    populate the city field with values from the database.
    Does anyone have an example of how to do this? I'm guessing it
    can be done using thin JDBC.
    Any help would be appreciated.
    Thanks
    J Mathew
    null

    Hi Ram
    for the first time when the page loads i want the trailing list to be empty ....
    so in the processRequest itself i call invokeMethod and append the whereclause in the voImpl .....if a do a System.out.println("Trailing List VO ::ROW COUNT IS : "+getRowCount()); immediately after executeQuery it returns 0 ...
    but some how on the page i get to see some records in the list....
    Let me know if anyother info is required ...
    Regards
    Sunny

  • Problem Populating Image Item From Database

    Hi All,
    I am using Oracle 9i & Forms 6i on Windows platform & working in client/server model. I created a form in which, I am reading an image file from the file system & then saving it into the database. In the Databse, i created the column as BLOB. But, when I query, this does not retrive the saved image in Image Item. But image is actually saved. When I tried, changing the database column to LONG RAW, it is working. I mean its reading the image in the image item from the database.
    Can anyone pls tell me, is there any problem like this, as we can retrive from LONG RAW but not from BLOB, or I am missin something here.
    Regards

    Hi,
    I use Forms 6i to save and retrieve image in BLOB column without problems.
    Some weeks ago, my column was long raw and I update it without problems. Nothing to do in Forms and juste modifiy query and recompile in Reports.

  • Populating a pdf from database with ASP

    Hi,
    I have been tasked to see if it is possible to fill in
    http://www.uses.doleta.gov/pdf/eta9061.pdf
    this government form and
    several others dynamically from a database.
    Does anyone have an idea if it can be done via ASP or am I
    looking at
    recreating each form with HTML and filling in that way.
    My main issue with this is if the government will accept the
    generated
    forms that way.
    Any ideas would be helpful.
    Thanks in advance

    > Does anyone have an idea if it can be done via ASP or am
    I looking at
    > recreating each form with HTML and filling in that way.
    > My main issue with this is if the government will accept
    the generated
    > forms that way.
    As a .gover myself, I have to deal with thie all the time.
    The core problem is that .gov is *still* run on paper-forms,
    and solutions
    like these are nothing but gigantic hacks that don't actually
    solve the core
    issue: distributing and collecting data electronically.
    If you zoom into that particular PDF example, you will note
    that it is not
    'electronic' at all.
    It's nothing more than a scanned piece of paper.
    So, to get this to where the client would be happy, you're
    going to have to
    first add PDF form fields to this PDF. Then be sure to put in
    the
    apporpriate labels and extra text to make it accessible. Then
    you need to
    create the data-base back end. Then you need to create an
    interface to get
    the data to and from the PDF.
    Then you're done.
    Until they decide to slightly change the form.
    Then look out.
    Ultimately, this is a really dumb way to go about it.
    Granted, it'll be a
    big chore to convince them of that. ;o)
    Ideally, you'd take the simple route, as simple is often
    better. Make a web
    form. Let people fill it out online. Once filled in, give
    them a printable
    HTML form back.
    Adobe has done an AMAZING job of firmly getting their foot in
    the .gov door,
    and it's going to be REALLY hard to pry that foot out, but
    hopefully we'll
    get there some day.
    -Darrel

  • Dataset not populating any data from database

    Hi All,
       I created a dataset in VS 2008 from a project database. In design view, when I right-click a table and select preview data, I can see the records. In Crystal Reports, I connected to the dataset and selected my tables. When I go to run the report, I get no data. When I try to browse data on one of the fields in a table, I get nothing either.
    What am I not doing to get the data across over to my report?
    Thank you in advance.

    Hi All,
       Here's the code I use:
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Dim ds As New Call_Records_Dataset
            Dim ta As New Call_Records_DatasetTableAdapters.Call_RecordsTableAdapter
            ta.Fill(ds.Call_Records)
            CrystalReportSource1.ReportDocument.SetDataSource(ds)
            parameterField2 = CrystalReportSource1.ReportDocument.ParameterFields("Date")
            parameterField2.CurrentValues.AddRange(Today, Today, RangeBoundType.BoundInclusive, RangeBoundType.BoundInclusive)
        End Sub
    When I run the website, it's giving me the following error: "The system cannot find the file specified" and refers me to "        CrystalReportSource1.ReportDocument.SetDataSource(ds)" line.

  • POPULATING THE JTABLE FROM DATABASE!!I need find out where im going wrong?

    for some reason wen i run the program the fields dont populate!!! no errors in my output monitor nothing? im puzzled! no errors in the code either!!! im using Netbeans IDE 6.0 with no code generators watsoever! i type out all type code myself! i have checked and rechecked and rechecked! been stuck here for two days! if anyone has code out there they are willing to share or possibly advice if u've had the same problem please let me know where to look or pass on the solution!
    Hurry Im losing a lot of hair!!!!!!
    Edited by: Dubs08 on Feb 7, 2008 10:36 PM

    code ?

  • JDBC:  Filling a combobox or listbox from a database

    How would I go about populating a combobox or listbox from a database query?
    What would the basic steps be? Do I need to create vectors?
    Is there a good reference place for this stuff on the Web?
    Thanks!

    What would the basic steps be? Do I need to create
    vectors?possible (not so clean):
    1. retrieve a resultset
    2. create a model with the set
    3. set the model of the listbox or the combobox
    4. call repaint
    Is there a good reference place for this stuff on the
    Web?http://developer.java.sun.com/developer/onlineTraining/
    Thanks!

  • Export to PDF from populated c# Dataset without Database connection

    I have Crystal Reports Developer Full version 11.5.12.1838, all versions of Visual Studio and about 100+ reports targeting printed paper.
    They were developed over the last decade with the Developer Designer (and it's predecessors) and are based on SQL Server Stored Procedures. In the past, they were produced at runtime using a MS Access VBA application that either printed them or exported them to PDF files. I have successfully converted that application to C#, however a few problems: despite loading a populated dataset and setting all parameters, the runtime still wants to refresh the dataset. That works for 95% of all reports, but some just use null values for the parameters (despite having set them correctly), others mix the sequence of the parameters (despite querying them correctly) and some don't use the provided credentials. But that is not the main problem.
    Now I need a way to produce (export to PDF) these reports at runtime based on a populated C# Dataset without database connectivity for the Crystal environment. The structure of the data in the Dataset is identical to what the stored procedure return in the development environment.
    The question is: is that possible and what do I need in terms of version, SDK etc. Any advice (sample links) would be much appreciated.

    Hi Ludek;
    Thanks for the hints. After many many hours of research and trial and error here are my findings:
    Assigning a dataset to CR does NOT work - seems CR is just ignoring it completely. What does (partially) work is assigning a DataTable, however, if you try to do that with a main report and more than ONE sub-report, it fails with likely unrelated error messages (not yet implemented).
    I took one of my reports and deleted all sub-reports. Assigned a DataTable at runtime - works fine. Added one sub-report that has a single field (picture) and loaded at runtime with a DataTable. No problem.
    Removed that subreport and added another subreport that has a single text field. All good.
    Now: having both sub-reports and having both subreports loaded from a DataTable fails. It works if one of the datasets is empty. It also works with 2 sub-reports returning text into their single field.
    The DataTables are populated from the exact same stored procedures (and data source) that are embedded in the report from the design (CR XI) - essentially this should be a swap from internal to external fetch with no consequences.
    I tried assigning using subDocument.SetDataSource and subDocument.Databas.Tables[0].SetDataSource  - no difference.
    The background of this: all my reports work just fine using VBA (Access), but that app will be retired and replaced by something C# based. In the meantime, the same report file has to work with both engines.
    If I cannot get the DataTable assignment for sub-reports to work, there is a plan-b type possibility: replacing the stored procedure for some sub-reports at runtime - which works using SubReport.Database.Tables[0].Location.= "newSPName" as long as the new sp has no parameters like the old one.
    The problem is that the new procedure has 2 parameters and I did not find a way to add them to the parameters collection (not allowed in sub-reports)
    Anything that comes to your mind ?
    Any help will be much appreciated
    Thanks
    Rolf

  • Populating menu items from the database...is it possible?

    hi
    using :forms 10g
    we have a requirement in forms where we need to populate the menu items from the database.first we used hiearchial tree where it was possible.but since the requirement changed i am not sure that whether the menu items can be populated by data from the database...will be glad if someone could throw some light on this issue...
    thanks

    You could always do it but would need to put a fix limit on the number of menu items.
    For example you could create a set of menu items at design time with the visible property set to False.
    While reading the database, you then set them to True while setting the label to whatever you require.
    But it all depends also on what you want your menu items to do when selected.

  • Populating fields from database values

    I have a page being populated from database values. I used the Application Builder Wizard to create the application. One of the fields is displaying on the report, but when I click edit, the value is not there. The field is defined as a float and being displayed as a text item. I have created this Application twice with the same results.
    Any ideas?
    thanks!
    Christie

    Thank you for the quick reply!
    I turned on the debug, to ensure the automatic fetch
    process it on and it is. The edit page has 7
    fields, all are being populated except for this one.
    I have confirmed it is using the correct database
    column and it is replacing the existing value the
    same as the other fields.
    Any other ideas to what could be going on?You can see each page item assignment in the debug output. Look there to see where the page item is being set, and potentially unset I suppose. The thing to look for here might be page processes that might be interacting with that item.
    You could also simply drop the problematic page item and recreate it to see if you can make the value stick.
    Earl

  • Jtree examples of populating data from database

    I have searched many of the solutions here, but the threads that contain examples of jtree loading from an sql database are not available. Does anyone have a good example of populating a jTree from the database?
    Thank You

    Hi,
    AFAIK, there is no direct approach to populate a JTree directly from a resultset. However, JTree can use a DOM tree as its model by using the adapter pattern. The procedure to do this is well-documented in the SUN website and the link is provided below. The code to convert a resultset to XML is provided below:
    protected void resultSetToXML(OutputStream out,
    ResultSet rs,
    String stylesheet)
    throws IOException, ServletException {
    // Create reader and source objects
    SqlXMLReader sxreader = new SqlXMLReader();
    SqlInputSource sis = new SqlInputSource(rs);
    // Create SAX source and StreamResult for transform
    SAXSource source = new SAXSource(sxreader, sis);
    StreamResult result = new StreamResult(out);
    // Perform XSLT transform to get results. If "stylesheet"
    // is NULL, then use identity transform. Otherwise, parse
    // stylesheet and build transformer for it.
    try {
    // Create XSLT transformer
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t;
    if (stylesheet == null) {
    t = tf.newTransformer();
    } else {
    // Read XSL stylesheet from app archive and wrap it as
    // a StreamSource. Then use it to construct a transformer.
    InputStream xslstream = _config.getServletContext().
    getResourceAsStream(stylesheet);
    StreamSource xslsource = new StreamSource(xslstream);
    t = tf.newTransformer(xslsource);
    // Do transform
    t.transform(source, result);
    } catch (TransformerException tx) {
    throw new ServletException(tx);
    The classes SQLXMLReader and other classes used in this example are available in the following java packages.
    import java.sql.*;
    import javax.sql.DataSource;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.sax.*;
    import javax.xml.transform.stream.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.AttributesImpl;
    The following is the link that explains how to load a JTree from DOM.
    http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPDOM6.html
    Cheers,
    vidyut

  • Want JTree e.g. of populating data from database.

    I want ur JTree example of populating data from database, can u plz give me that eg.?
    Awaiting 4 ur reply.

    Hi,
    AFAIK, there is no direct approach to populate a JTree directly from a resultset. However, JTree can use a DOM tree as its model by using the adapter pattern. The procedure to do this is well-documented in the SUN website and the link is provided below. The code to convert a resultset to XML is provided below:
    protected void resultSetToXML(OutputStream out,
    ResultSet rs,
    String stylesheet)
    throws IOException, ServletException {
    // Create reader and source objects
    SqlXMLReader sxreader = new SqlXMLReader();
    SqlInputSource sis = new SqlInputSource(rs);
    // Create SAX source and StreamResult for transform
    SAXSource source = new SAXSource(sxreader, sis);
    StreamResult result = new StreamResult(out);
    // Perform XSLT transform to get results. If "stylesheet"
    // is NULL, then use identity transform. Otherwise, parse
    // stylesheet and build transformer for it.
    try {
    // Create XSLT transformer
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t;
    if (stylesheet == null) {
    t = tf.newTransformer();
    } else {
    // Read XSL stylesheet from app archive and wrap it as
    // a StreamSource. Then use it to construct a transformer.
    InputStream xslstream = _config.getServletContext().
    getResourceAsStream(stylesheet);
    StreamSource xslsource = new StreamSource(xslstream);
    t = tf.newTransformer(xslsource);
    // Do transform
    t.transform(source, result);
    } catch (TransformerException tx) {
    throw new ServletException(tx);
    The classes SQLXMLReader and other classes used in this example are available in the following java packages.
    import java.sql.*;
    import javax.sql.DataSource;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.sax.*;
    import javax.xml.transform.stream.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.AttributesImpl;
    The following is the link that explains how to load a JTree from DOM.
    http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPDOM6.html
    Cheers,
    vidyut

  • [b] Populating List Box from MySQL Database[/b]

    Hi all,
    I'm trying to populate a JComboBox from MySQL database, I Have an applet which send's the query to a server through sockets on the localhost, but when i try to retrieve the result set from the MySQL database, i get an index out of bounds exception, It's probably something simple, any help regarding the above problem!! I've included the code below!!
    Cheers
    Dave
    java.lang.ArrayIndexOutOfBoundsException: 1
    at dbWrapper1.Select(dbWrapper1.java:97)
    at TestUpdateDB.main(TestUpdateDB.java:29)
    Applet Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    *     @version  04/18/05
    *     @author David Lawless
    public class cust extends JApplet implements ActionListener
    //Declare Labels for Form
    private JLabel titleLabel;
    private JLabel firstNameLabel;
    private JLabel lastNameLabel;
    private JLabel addressLabel;
    private JLabel countyLabel;
    private JLabel countryLabel;
    //Declare Input fields for user
    private JTextField firstNameText;
    private JTextField lastNameText;
    private JTextField addressLineOneText;
    private JTextField addressLineTwoText;
    private JTextField addressLineThreeText;
    //Declare list for title box
    private JComboBox titleList;
    private String[] title = {"Mr.","Mrs.","Miss","Ms","Dr."};
    //Declare list for county box
    private JComboBox countyList;
    //Called when this applet is loaded into the browser.
    public void init()
    lookAndFeel();
    //Initialise Labels
    firstNameLabel = new JLabel("First Name * ");
    lastNameLabel = new JLabel("Last Name * ");
    titleLabel = new JLabel("Title * ");
    addressLabel = new JLabel("Address *");
    countyLabel = new JLabel("County *");
    countryLabel = new JLabel("Country *");
    //Initialise title List
    titleList = new JComboBox( title );
    titleList.setActionCommand("Title");
    //Set up Text fields
    firstNameText = new JTextField(30);
    firstNameText.setToolTipText("Please enter your first name here");
    lastNameText = new JTextField(30);
    lastNameText.setToolTipText("Please enter your surname here");
    addressLineOneText = new JTextField(30);
    addressLineTwoText = new JTextField(30);
    addressLineThreeText = new JTextField(30);
    //Retrieve County List From Database
    //countyList = new JComboBox( counties );
    try
         try
              Socket mySocket = new Socket ("127.0.0.1", 1983 );
              ObjectOutputStream out = new ObjectOutputStream(mySocket.getOutputStream());
              String entry1 ="SELECT county FROM data";
              out.writeObject(new String(entry1));
              ObjectInputStream in = new ObjectInputStream(mySocket.getInputStream());
              int size = in.readInt();
              Object [] results = new Object[size];
              for (int i=0; i < size  ; i++ )
                   results[i] = in.readObject();
              countyList = new JComboBox( results );
              countyList.setActionCommand("County");
              mySocket.close ();
         catch (Exception exp)
              exp.printStackTrace();
    // detect problems interacting with the database
    catch ( Exception sqlException )
         System.exit( 1 );
    //set up command buttons
    submitButton = new JButton("Submit");
    submitButton.setToolTipText("Click here to submit your details ");
    submitButton.addActionListener(this);
    cancelButton = new JButton("Cancel");
    cancelButton.setToolTipText("Click here to cancel order");
    cancelButton.addActionListener(this);
    Container topLevelContainer = getContentPane();
    getContentPane().setBackground(Color.blue);
    //Create Layout
    JPanel contentPane = new JPanel();
    //Set transparent background instead of blue
    contentPane.setBackground(Color.white);
    contentPane.setLayout(null);
    contentPane.setOpaque(true);
    titleLabel.setBounds(37,10,75,20);
    contentPane.add(titleLabel);
    firstNameLabel.setBounds(93,10,100,20);
    contentPane.add(firstNameLabel);
    lastNameLabel.setBounds(198,10,100,20);
    contentPane.add(lastNameLabel);
    titleList.setBounds(37,35,50,20);
    contentPane.add(titleList);
    firstNameText.setBounds(93,35,100,20);
    contentPane.add(firstNameText);
    lastNameText.setBounds(198,35,100,20);
    contentPane.add(lastNameText);
    addressLabel.setBounds(37,65,100,20);
    contentPane.add(addressLabel);
    addressLineOneText.setBounds(37,90,125,20);
    contentPane.add(addressLineOneText);
    addressLineTwoText.setBounds(37,115,125,20);
    contentPane.add(addressLineTwoText);
    addressLineThreeText.setBounds(37,140,125,20);
    contentPane.add(addressLineThreeText);
    countyLabel.setBounds(37,165,100,20);
    contentPane.add(countyLabel);
    countyList.setBounds(37,190,100,20);
    contentPane.add(countyList);
    submitButton.setBounds(60,250,100,20);
    contentPane.add(submitButton);     
    cancelButton.setBounds(180,250,100,20);
    contentPane.add(cancelButton);
    topLevelContainer.add(contentPane);
    }//End init()
    static void lookAndFeel()
         try
              UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
         catch(Exception e)
    }//End look and feel method
    public synchronized void actionPerformed(ActionEvent e)
    String actionCommand = e.getActionCommand();
    if (e.getSource() instanceof JButton)
         if (actionCommand.equals("Cancel"))
                   int returnVal = JOptionPane.showConfirmDialog(null,
                        "Are you sure you want cancel and discard your order?",
                        "Cancel Order", JOptionPane.YES_NO_OPTION);
                   if(returnVal == JOptionPane.YES_OPTION)
                        System.exit(0);
         if (actionCommand.equals("Submit"))
              firstName = firstNameText.getText();
              Surname = lastNameText.getText();
         }//end action command for submit button
    }//end method actionperformed
    }//End class customerDatabase Connection Code:
    import java.sql.*;
    import java.util.*;
    class dbWrapper1
        private Statement statement;
        private Connection connection;
        private String strUserName;
        private String strPassword;
         Object [] results = null;
         static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
         static final String DATABASE_URL = "jdbc:mysql://localhost:3306/ecommerce";
        public dbWrapper1()
            // the DSN for the Db connection
            strUserName = "root";
            strPassword = "password";
        public void Open()
            try
                // Load the jdbc-odbc bridge driver
                Class.forName ( JDBC_DRIVER );
                   //                    ***** TESTING PURPOSES *****
                   //Check currently loaded drivers
                   System.out.println("Currently loaded drivers...");   
                   for
                        Enumeration enum1 = DriverManager.getDrivers() ;
                        enum1.hasMoreElements();
                   System.out.println(enum1.nextElement().getClass().getName());
                // Attempt to connect to a driver.
                connection = DriverManager.getConnection ( DATABASE_URL, strUserName, strPassword );
                // Create a Statement object so we can submit
                // SQL statements to the driver
                statement = connection.createStatement();
            catch (SQLException ex)
                while (ex != null)
                    System.out.println ("SQL Exception:  " + ex.getMessage () );
                    ex = ex.getNextException ();
            catch (java.lang.Exception ex)
                ex.printStackTrace ();
        public void Update( String strUpdate )
            try
                // Submit an update or create
                statement.executeUpdate( strUpdate );
              catch (SQLException ex)
                while (ex != null)
                    System.out.println ("SQL Exception:  " + ex.getMessage () );
                    ex = ex.getNextException ();
        public Object[] Select( String strQuery )
            try
                // Submit a query, creating a ResultSet object
                ResultSet resultSet = statement.executeQuery( strQuery );
                // process query results
                   ResultSetMetaData metaData = resultSet.getMetaData();
                   int numberOfColumns = metaData.getColumnCount();
                   results = new Object[numberOfColumns];
                   while ( resultSet.next() )
                        for ( int i = 1; i <= numberOfColumns; i++ )
                             results[i] = resultSet.getObject(i);
                             System.out.print(resultSet.getString(i) + " | " );
                        System.out.println();
                   resultSet.close();
            catch (SQLException ex)
                while (ex != null)
                    System.out.println ("SQL Exception:  " + ex.getMessage () );
                    ex = ex.getNextException ();
              for (int i=0;i<results.length ;i++ )
                   System.out.println(results);
              return results;
    public void Close()
    try
    statement.close();
    connection.close();
    catch (SQLException ex)
    while (ex != null)
    System.out.println ("SQL Exception: " + ex.getMessage () );
    ex = ex.getNextException ();
    Server Code:
    import java.io.*;
    import java.net.*;
    public class TestUpdateDB
         public static void main(String[] args)
              System.out.println ( "Server is active" );
              try {
              ServerSocket sock = new ServerSocket ( 1983 );
              while ( true )
                   try
                        Socket mySock = sock.accept();
                        ObjectInputStream iStream = new ObjectInputStream(mySock.getInputStream());
                        ObjectOutputStream oStream = new ObjectOutputStream(mySock.getOutputStream());
                        Object temp = iStream.readObject();
                        String entry = (String)temp;
                        System.out.println ( entry );
                        dbWrapper1 myDB = new dbWrapper1();
                        myDB.Open();
                        Object [] query = myDB.Select(entry);
                        int size = query.length;
                        oStream.writeInt(size);
                        for (int i=1 ; i <= query.length ; i++)
                             oStream.writeObject( query );
                        myDB.Close();
                   catch ( Exception exp )
                        exp.printStackTrace ();
              catch ( Exception exp ) {
                exp.printStackTrace();

    Sir,
    The exception is probably in here.
    for ( int i = 1; i <= numberOfColumns; i++ ){
      results[i] = resultSet.getObject(i);
      System.out.print(resultSet.getString(i) + " | " );
    }ResultSet counting begins with 1 but array indexing begins with 0 your code should look more like.
    for ( int i = 0; i <= numberOfColumns; i++ ){
      results[i] = resultSet.getObject(i+1);
      System.out.print(resultSet.getString(i+1) + " | " );
    }Sincerely,
    Slappy

Maybe you are looking for

  • [SOLVED] hdparm -S 241 no longer working

    Sometime in the last month, hdparm has stopped spinning down defined HDD's. I have a total of three HDD's in my system. Al rotating media. Two of those HDD's I use for backup, and as such are not needed for most of the day. In my rc.local I have: hdp

  • Firefox does not close correctly and needs to be closed in the task manager.

    when trying to close firefox, it goes off screen, but cannot be reopened until I go through task manager to close it.

  • Singleton vs static - which is better?

    Of the two approaches - a class which can be used by accessing its ONLY instance(singleton) or a class which has a set of static methods which can be invoked on the class itself which is better and why? Or are these just two 'styles' of programming?

  • Advanced DataGrid SUM

    Hi All, I'm trying to SUM columns and display the total column at the end of each group using: <mx:GroupingCollection id="groupedData" source="{acData}" >                             <mx:Grouping>                                 <mx:GroupingField nam

  • Newbie: Jdev's intelisense not working for HOUR_OF_DAY

    I'm using Jdev preview 4. Suppose I have below code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ page contentType="text/html;charset=windows-1252"%> <html> <head> <meta http-equiv="Conten