Populating table from database

Number FoodItem Quantity Price Description
1     Rice     1 bag     5000 Carbohydrate
2     Beans     1 bag     4000 Protein
3     Palm Oil 1 bottle 500 Fats & Oil
i have a table like this in my database,need help in populating my list
with "FoodItem" from the database when my GUI comes up.Also,want to display final result of selection in my table.
'\n'
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import static javax.swing.GroupLayout.Alignment.*;
import java.sql.*;
import java.util.*;
public class Foodtable extends JFrame {
     //private JButton finish,view;
     private JTable table;
     private DefaultTableModel model;
     private JScrollPane pane,pane1;
     private JTextField currentamount,totalamount,qtyfield;
     private JList foodlist;
     private JComboBox box;
     private String[] qtybox={"cup","mudu","bag"};
     private DefaultListModel lm;
     Connection con=null;
     Statement st=null;
     private static ResultSet rs;
     public Foodtable(){
          JPanel p1 = new JPanel();
          p1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Food List",TitledBorder.CENTER,TitledBorder.TOP));
          p1.setLayout(null);
          p1.setPreferredSize(new Dimension(170,150));
          lm = new DefaultListModel();
          foodlist = new JList(lm);
          pane1 = new JScrollPane(foodlist);
          pane1.setBounds(10,20,148,180);
          p1.add(pane1);
          JLabel qty = new JLabel("Quantity:");
          qty.setBounds(10,210,60,20);
          p1.add(qty);
          qtyfield = new JTextField(5);
          qtyfield.setBounds(65,210,30,20);
          p1.add(qtyfield);
          box = new JComboBox(qtybox);
          box.setBounds(95,210,60,20);
          p1.add(box);
          JPanel p2 = new JPanel();
          p2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Food Table",TitledBorder.CENTER,TitledBorder.TOP));
           model = new DefaultTableModel();
           model.addColumn("Number");
           model.addColumn("Food Item");
           model.addColumn("Quantity");
           model.addColumn("Price");
           model.addColumn("Description");
          table = new JTable(model);
          pane = new JScrollPane(table);
          pane.setPreferredSize(new Dimension(300,140));
          p2.add(pane);
          JPanel p = new JPanel();
          GroupLayout layout = new GroupLayout(p);
          p.setLayout(layout);
          layout.setAutoCreateGaps(true);
          layout.setAutoCreateContainerGaps(true);
          layout.setHorizontalGroup(layout.createSequentialGroup()
               .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                         .addComponent(p1)
                    .addComponent(p2)
          layout.setVerticalGroup(layout.createSequentialGroup()
               .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(p1)
                    .addComponent(p2)
          JPanel p4 = new JPanel();
          p4.setLayout(null);
          p4.setPreferredSize(new Dimension(200,30));
          /*finish = new JButton("Finish");
          finish.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
          finish.setRolloverEnabled(false);
          finish.setBounds(170,20,60,20);          
          p4.add(finish);*/
          JLabel currentlabel = new JLabel("Current Amount:");
          currentlabel.setBounds(300,10,100,20);
          p4.add(currentlabel);
          currentamount = new JTextField();
          currentamount.setBounds(395,10,50,20);
          currentamount.setEditable(false);
          p4.add(currentamount);
          JLabel total = new JLabel("Amount Spent:");
          total.setBounds(300,30,100,20);
          p4.add(total);
          totalamount = new JTextField();
          totalamount.setBounds(395,30,50,20);
          totalamount.setEditable(false);
          p4.add(totalamount);
          GroupLayout flayout = new GroupLayout(getContentPane());
          getContentPane().setLayout(flayout);
          flayout.setAutoCreateGaps(true);
          flayout.setAutoCreateContainerGaps(true);
          flayout.setHorizontalGroup(flayout.createSequentialGroup()
               .addGroup(flayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(p)
                    .addComponent(p4)
          flayout.setVerticalGroup(flayout.createSequentialGroup()
               .addGroup(flayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addGroup(flayout.createSequentialGroup()
                         .addGroup(flayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                              .addComponent(p)
                    .addComponent(p4)
          setSize(640,460);
          setDefaultCloseOperation(EXIT_ON_CLOSE);
     public static void main(String[] arg){
          new Foodtable().setVisible(true);
     public void showRecord(){
          try{
               Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
               con = DriverManager.getConnection("jdbc:odbc:food","","");
               st = con.createStatement();
               rs=st.executeQuery("SELECT*FROM tbl_food");
               while(rs.next()){
                    lm.addElement(rs.getString("food_name"));
          catch(Exception sqle){
               JOptionPane.showMessageDialog(null,"Exception.......\n" + sqle.getMessage() ,"Error Information",JOptionPane.ERROR_MESSAGE);
     /*public void query(){
          try{
               Class.forName("com.mysql.jdbc.Driver");               
               con = DriverManager.getConnection("jdbc:mysql://localhost/food?user=password=");
               st = con.createStatement();
               String sql = "SELECT foodlist.food,foodlist.description FROM foodlist";
               rs = st.executeQuery(sql);
               while(rs.next()){
                    lm.addElement(rs.getString(1)+'\n');
          }catch(Exception ee){
               System.out.println(ee);
          finally{
               try{
                    st.close();
                    con.close();
               }catch(Exception ex){ System.err.println(ex);}
     public void actionPerformed(ActionEvent e){
          Object[] value = foodlist.getSelectedValues();
          if(e.getSource()==view){
               query();
          if(e.getSource() == move){
               for(int i=0;i<value.length;i++){
                    String word = (String)value;
                    //String foodclass = rs.getString("foodlist.description");
                    Vector<Object> data = new Vector<Object>();
                    data.addElement(word);
                    data.addElement(qtyfield.getText()+" "+box.getSelectedItem());
                    data.addElement("");
                    //data.addElement("foodclass");
                    model.addRow(data);

This particular forum is about jdbc. Do you have a question about jdbc?
If so then what specifically is it?
If you have questions about GUIs (display, buttons, events, etc) then there are other forums for that.

Similar Messages

  • OBIEE Error while importing table from database

    Hi
    I am getting the following error when i am trying to import table from database.
    [nQSError: 16001]ODBC error state: IM004 code:0 message:
    [Microsoft][ODBC Driver Manager] Driver`s SQLAllocHandle on SQL_HANDLE_ENV failed.
    Any idea y such error.
    Thanks and Regards,
    Andy

    Looks like an error in the ODBC driver, not OBIEE as such.
    Have you tried googling it?
    Can you post details about your OS and DB.

  • [nQSError: 46115] - Admin Tools: can't import table from database .

    hi all,
    Need your help, i am using Bi Administration Tool, and i try to import tables from database,but encounter issue:
    (1)."File->import->from database...",select connection type as OCI 10g/11g, type TNS Name,User Name and Password,then click "OK".
    (2).select table "BI_DATA",and then click button "import",it show prompt:"Failed to perform requested action".
    (3).i try to click the symbol "+" on the left of table "BI_DATA", it show below prompt:
    [nQSError: 46115] No Unicode translation is available for some of the input characters for MultiByteWideChar().
    is there anyone can help me? thanks.
    the BI version is:
    Build: 10.1.3.4.1.090414.1900
    Release Version: Oracle Business Intelligence 10.1.3.4.1
    Package: 090414.1900

    I meet the problem, too! I can't solve it. Is anyone who can help me.
    My email is [email protected]
    thanks in avdvanced!

  • How to display multiple tables from database using netbeans swing gui

    plz reply asap on how to display multiple tables from database using netbeans swing gui into the same project

    Layered Pane with JTables or you can easily to it with a little scripting and HTML.
    plzzzzzzzzzzzzzzzzz, do not use SMS speak when posting.

  • 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

  • Labview 2013 are closing when I try read table from database.

    Labview 2013 are closing when I try read table from database.
    I don't get error message, Labview just crashes. I'm use Labview x32 and Database Connectivity Toolkit connective on Windows 7 x64. I connect to PostgreSQL with ODBC driver, connection is stable.
    In my database I have many tables, I can read all them without one.
    When I try read bad table I get data and then labview crash. When I restart Labview I don't have any message about error.
    Also I try use LabSQL-1.1a. But it has same result.
    Solved!
    Go to Solution.
    Attachments:
    DBT.png ‏104 KB
    LabSQL.png ‏67 KB

    Try connecting using UDL file. What operation you are doing with database
    You can create the same.. Do this Tools --> Create Data link..
    Then go to http://www.ni.com/pdf/manuals/371525a.pdf link and see page 3-5. It will help
    Kudos are always welcome if you got solution to some extent.
    I need my difficulties because they are necessary to enjoy my success.
    --Ranjeet

  • Is it possible to update internal table from database table

    Hello All:
              I know how to update database table from internal table in one shot (batch) but is the reverse possible? Can I update some fields in an internal table from a database table in one shot (without looping) because my internal table is huge? Could you please provide me any ideas how to acheive something like this? Thanks in advance and answers will be rewarded.
    thanks.
    Mithun

    Hello my friend,
    You can do it MAYBE , i think you can reverse the update doing a ROLLBACK, but only after you update....not after the program finishes..
    To update some fields at once use:
    UPDATE DBTABLE FROM TABLE IT_TABLE
    Hope this helps!!
    Gabriel

  • Error in importing the tables from database

    HI ,
    while importing the table from the metada by using OCI call 10g/11g i am getting the below exception:
    *"Some objects are not imported because of invalid names : (DESCRIPTION =(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=orcl)))"*
    i am getting this exception after selecting the objects which i want to import from the database.....it first imports the tables and the throws the above exception and then removies from the repository view.
    How can i get this resolved???

    Hi,
    I'm also hitting this problem, did anyone solve this, I'm not able to import any data to the repository, error message is: -
    *"Some objects are not imported because of invalid names"*
    Thanks,
    Mike

  • Display data in Web DynPro table from database via EJB

    I have a JavaBeans model which has a method populateDataToTable()to retrieve data from database via Session bean (calling entity bean, returning ArrayList of data) and the data needed to be display in the Web DynPro table.
    User Interface (Web DynPro) <-> JavaBeans Model <-> Busineess Logic (session bean) <-> Persistence (Entity Bean)<-> DB table.
    The context bindiing and table part is ok. How do i load the data to the table ? what the coding to put in wdDoInit() ?
    Any help would be appreciated.

    in wdinit(),
    Collection col = new ArrayList();
    try{                    
      MyCommandBean bean = new MyCommandBean();
      col = bean.getDataFromDbViaEJB();
      wdContext.nodeMyCommandBean().bind(col);
    } catch (Exception ex) {
       ex.printStackTrace(ex); 
    in your JavaBean model class, MyCommandBean getDatafromDbViaEJB() method:
    Collection col = new ArrayList();
    Collection newcol = new ArrayList();
    //include your own context initialization etc...
    col = local.getDataViaSessionBean(param);
    // if your returned result also a bean class, reassigned it to current MyCommandBean
    for (Iterator iterator = col.iterator(); iterator.hasNext();) {
        MyOtherBean otherBean=(MyOtherBean)iterator.next();
        MyCommmandBean bean = new MyCommandBean();
        bean.attribute1 = outBean.getAttirbute1();
        // get other attibutes
        newcol.add(bean);
    return newcol;

  • Query builder: tables from Database Link

    Hi APEX people,
    Is there a way to use tables from a (remote) Database Link in the Query Builder?
    In the Query Builder I seem to have only access to locally (schema) stored tables.
    I already tried to define a Synonym for the remote tables I wanted to use, but that didn't work either.
    Thanks in advance.
    Maurice

    Hi,
    First of all, can you select from them ie
    SELECT  *
    FROM my_table@my_linkAlso you can't see them as tables in the schema because they're not tables in the schema.
    Try creating a view like...
    CREATE OR REPLACE FORCE VIEW m_table_vw AS
    SELECT *
    FROM my_table@my_link;You should be able to see the view in the schema in the query builder and use that.
    Cheers
    Ben

  • Populating JTree from database

    Hi experts,
    I need some feedbacks about the way i populate my JTree from database, Is there any better alternatives?
    If yes, try explain it in detail.. I'm still new in Java.
    Sample database table:
    |       node_id      |       name      |       parent       |       hasChild      |
    |         1          |     garbage     |        null        |           1         |
    |         2          |       item      |          1         |           1         |
    |         3          |      mouse      |          2         |           0         |
    |         4          |       board     |          2         |           0         |
    |         5          |       item2     |          1         |           1         |
    |         6          |       item3     |          1         |           1         |
    |         7          |       pants     |          5         |           0         |
    -----------------------------------------------------------------------------------Here's the sample of my code:
    //... ResultSet rs = .....
    rs.last();
    int rowCount = rs.getRow(); //Get the total number of row in database table
    rs.beforeFirst();
    int i = 0;
    int j = 0;
    String [] nodeID = new String[rowCount];  //The node ID
    String [] parentID = new String[rowCount];  //A pointer to its parent ID
    DefaultMutableTreeNode [] node = new DefaultMutableTreeNode[rowCount]; //The node
    while(rs.next()) {
         String name = rs.getString("name");
         Boolean bool = rs.getBoolean("hasChild");
         node[i] = new DefaultMutableTreeNode(name,bool);
         parentID[i] = rs.getString("parent");
         nodeID[i] = rs.getInt("node_id") + "";
            //Set as root node when the pointer is null               
         if(parentID.equals("null")) {
              rootNode = node[i];
         i++;
    for(i=0; i<rowCount; i++) {
         for(j=0; j<rowCount; j++) {
              if(parentID[j].equals(nodeID[i]) && node[i] != null) {
                   node[i].add(node[j]);
    node[i] = null; //Obligates the parent after finish adding the child (to prevent unnecessary loops)
    //... tree = new JTree(rootNode);
    Thanks for the trouble,
    Regards,
    David

    The execution time are base on the code i post'ed here.
    Average over 30times using Vector = 640048 nanosecond to execute.
    Vector<String> nodeID = new Vector<String>();
    Vector<DefaultMutableTreeNode> node = new Vector<DefaultMutableTreeNode>();
    Vector<String> parentID = new Vector<String>();
    rs.last();
    int rowCount = rs.getRow();
    rs.beforeFirst();
    k=0;
    while(rs.next()) {
         String name = rs.getString("name");
         Boolean hasChild = rs.getBoolean("hasChild");
         node.addElement(new DefaultMutableTreeNode(name,hasChild));
         nodeID.addElement(rs.getInt("node_id")+"");
         parentID.addElement(rs.getString("parent"));
         if(parentID.elementAt(k).equals("null")) {
              rootNode = node.elementAt(k);
         k++;
    i=0;
    while(i<rowCount) {
         j=0;
         while(j<rowCount) {
              if(parentID.elementAt(j).equals(nodeID.elementAt(i)) && node.elementAt(j) != null) {
                   node.elementAt(i).add(node.elementAt(j));
                   if(!node.elementAt(i).getAllowsChildren())
                        node.insertElementAt(null,j);
              j++;
         i++;
    }Average over 30times using LinkedList = 95623 nanosecond to execute.
    //This section will have a class Nodes
    LinkedList<Nodes> gather = new LinkedList<Nodes>();
    while(rs.next()) {
         node = new DefaultMutableTreeNode(rs.getString("name"),rs.getBoolean("hasChild"));                    
         gather.add(new Nodes(rs.getInt("node_id") + "",node,rs.getString("parent")));
    for(Nodes findParent : gather) {                    
         if(findParent.getParentID().equals("null")) {
              findParent.setRoot(findParent.getNode());
              rootNode = findParent.getRoot();
         for(Nodes findChild : gather){
              if(findChild.getParentID().equals(findParent.getNodeID()))
                   findParent.getNode().add(findChild.getNode());               
    }As for the Array method i used from the previous post, the Average code execution time is x3 larger than the vector i used. So please do not use that method.
    Note: 1. The code i post can be improved further. 2. Execution time is based on individual computer.
    Well, I think i'll stop here. Anyone who wanted to know which method is more efficient currently, here's the answer.
    Hope that it helps anyone who have the problem here =).
    Edited by: DavidTW on May 23, 2011 3:14 PM
    Improved Version : Using for-each loop ( Effective Java, Second Edition, Joshua Bloch, Pg. 210).

  • 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

  • Seeing tables from database conection for a user

    I created a bunch of tables under a db admin
    I created a user aaa
    I granted all priveliges on all tables created to user aaa including "CREATE CONNECTION"
    I created a JDev Database connection through user aaa
    Test connection works fine. I open up the connection and try to look at the created tables. No tables! The display is empty
    I can see the tables from admin user connection fine. Why can't the connection through user aaa see the tables?
    Oracle 11g; JDev 11g P4
    Thanks
    Doug

    Hi,
    doesn't reproduce for me. Please make sure the user has granted select on the other user's tables
    Frank

  • Very very urgent. population data from database into dropdownbox

    Hi,
    i imported a model through ejbs
    this is to create new entries into database ,
    and my scenerio iso now i need to populate the values that i stored into database thro EJBS in a drop down box of wd application.
    plz help me through code ,i am new to java webdynpro...
    neede very urgently,
    Thanx .
    Arjun.G
    Message was edited by:
            arjun swamy

    Hi,
    Have a look at these threads
    Dropdown by index in table - fetching values from database
    Dropdown by index
    Kind Regards,
    Saravanan K

  • Populating table from csv

    Hi all .. i need the syntax for populating a table from hard drive stored csv file. there are 6 fields in target table (named orgs) and i want to populate its fields 'in' and 'out' from csv file. can someone plz help me? for the time being i m doing it manually by creating scripts in excell sheet but thats not a good approach. i m using oracle 9i. thanx in advance

    Hi,
    Take this example:
    I made a directory 'scott_dir' in my drive & put my csv file in it.
    Then i created an external table using the following:
    create table emp_ext (
    EMPNO NUMBER(4),
    ENAME VARCHAR2(10),
    JOB VARCHAR2(9),
    MGR NUMBER(4),
    HIREDATE DATE,
    SAL NUMBER(7,2),
    COMM NUMBER(7,2),
    DEPTNO NUMBER(2))
    Organization external
    (type oracle_loader
    default directory scott_dir
    access parameters (records delimited by newline
    fields terminated by ',')
    location ('emp_ext.csv'))
    reject limit 1000;
    It will insert data from your csv file to the emp_ext table.
    You can verify data using the Select statement.
    Later on you can merge data in your original table.
    Thanks

Maybe you are looking for

  • I need Native Code for my code

    can anyone tell me native code for my method .. BOOL CALLBACK DetectProcesses(HWND hwnd, LPARAM lParam)      char str[60] ;      ::GetWindowText(hwnd, str, 60) ;      CListBox listbox = (CListBox )lParam ;      if( str[0] != 0 )           listbox->Ad

  • Germany.vs.Brazil.Live.Stream.Online

    http://freerice.com/content-group/germanyvsbrazillivestreamonline http://freerice.com/content-group/germanyvsbrazillivestreamonline http://freerice.com/content-group/germanyvsbrazillivestreamonline http://freerice.com/content-group/germanyvsbrazilliv

  • Failure to connect to an external drive

    I have saved a number of files from my old PC to an external drive (WD) to tranfer them to my Mac. Trying to connect the drive the drive gets recognised in Finder (get a number a identity in Finder but also the message "Connection Failure". Trying to

  • Boot Camp doesn't detect keyboard

    Here's what happens: I start the Boot Camp assistant. It downloads the latest software from Apple, creates the driver disc (successfully). It then asks to reboot, which I do. Upon reboot, I am presented with a black screen asking me what CD option I'

  • Configure NWA

    Hi All, I am new to NWA , i logged into NWA but i am not able to click the define system selection and the following error messages appear 1. System Landscape Directory is not accessible 2. Only local system can be administered Can anyone help me out