Results 1 to 9 of 9
Like Tree1Likes
  • 1 Post By camickr

Thread: unable to add JTable data into microsoft access!!! please help me with the code!

  1. #1
    cute is offline Member
    Join Date
    Nov 2011
    Posts
    6
    Rep Power
    0

    Default unable to add JTable data into microsoft access!!! please help me with the code!

    Java Code:
    import java.util.*;
    
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    
    
    import java.sql.*;
    
    
    
    public class MyCoursework extends JFrame {
      Connection conn;
         Statement s;
     private String[] columnNames ={};
      private Object[][] data = {};
      ArrayList records= new ArrayList();
      
      JPanel panInput= new JPanel(new GridLayout(3,1)),
              panAdd= new JPanel();
              
        
       JTextField txtid = new JTextField(5),
                  txtName= new JTextField(10),
                  txtCost= new JTextField(5),
                  txtType= new JTextField(5),
                  txtDesc =new JTextField(20);
    JButton btnAdd = new JButton("Add"),
            btnDelete = new JButton("Delete"),
            btnSort = new JButton("Sort DVD"),
            btnSave= new JButton("Save"),
            btnReset =new JButton("Reset");
     
     private DefaultTableModel tabMod = new DefaultTableModel(
    
        data, columnNames);
    
    
    
      // Create a table
    
      private JTable table = new JTable(tabMod);
    public MyCoursework(){
    super("DVD list");
    table.setModel(tabMod);
    tabMod.addColumn("ID");
    tabMod.addColumn("name");
    tabMod.addColumn("cost");
    tabMod.addColumn("Type ");
    tabMod.addColumn("description");
    
    
    table.setVisible(true);
    btnAdd.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent ae){
      DVD_ListaddRecords();
      }  
            
    });
    
       btnSort.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent ae){
      sortRecords();
      }  
            
    });
    
    
    
    
    btnReset.addActionListener(new ActionListener(){
    public  void actionPerformed(ActionEvent ae){
    resetRecords();
    
    }
    
    });
    btnSave.addActionListener(new Listener());
    panAdd.add(btnSave);
    btnDelete.addActionListener(new Listener());
    panAdd.add(btnDelete);
    panAdd.add(btnAdd);
    panAdd.add(new JLabel("ID:"));
    panAdd.add(txtid);
    panAdd.add(new JLabel("DVD Name:"));
    panAdd.add(txtName);
    panAdd.add(new JLabel("Price:"));
    panAdd.add(txtCost);  
    panAdd.add(new JLabel("DVD Type:"));
    panAdd.add(txtType);
    panAdd.add(new JLabel("DVD description:"));
    panAdd.add(txtDesc);
    panAdd.add(btnReset);
    panAdd.add(btnSort);
    
    panAdd.setBackground(Color.pink);
    panInput.add(panAdd);
    
    
         this.getContentPane().setLayout(new GridLayout(1,2));
                
    
    Container cp = getContentPane();
            cp.add(panInput, BorderLayout.NORTH);
            cp.add(new JScrollPane(table));
            
            
     
     try
    
            {
    
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    
                JOptionPane.showMessageDialog(null,"Driver loaded");               
    
            }
            
            catch (Exception ex)
    
           {
              ex.printStackTrace();
    
           }
    
            
           getTableData(table); 
            
            
    setResizable(false);
    }
       class Listener implements ActionListener
    
       {
    
            @Override
            public void actionPerformed(ActionEvent e)
    
            {
    
                     if(e.getSource() == btnSave)
    
                     {
    
                        try
    
                        {
    
                             // Establish a connection
    
                             conn = DriverManager.getConnection
    
                             ("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=dvdrecords.mdb;");
    
                             System.out.println("Databse Connected");
    
                 
    
                              s = conn.createStatement();
    
                          String sql = "INSERT INTO dvdlist(ID,name,cost,type,description)VALUES("+"'"+txtid.getText()+"',"+"'"+txtName.getText()+"',"+"'"+txtCost.getText()+"',"+
                               "'" + txtType.getText()+"',"+"'"+txtDesc.getText()+"');";
    
                        PreparedStatement ps = conn.prepareStatement(sql);
                        columnNames[0]=txtid.getText();
                        columnNames[1]=txtName.getText();
                        columnNames[2]=txtCost.getText();
                        columnNames[3]=txtType.getText();
                        columnNames[4]=txtDesc.getText();
                        tabMod .insertRow(0,columnNames);
                                  
            
    
                         TableModel tm = table.getModel();
    
                         
    
                         int nRow = tm.getRowCount(), nCol = tm.getColumnCount();
    
                         System.out.println( " rows:" + nRow + "columns:" + nCol);
    
                            for(int r = 0;r < nRow; r++)
    
                            {
    
                                for(int c = 1;c <= nCol;c++)
                           {
    
                                       // ps.setObject(c, tm.getValueAt(r, (nCol-1)));
    
                                       if (c == 1 )
    
                                       {
    
                                        ps.setString(c, tm.getValueAt(r, nCol-1).toString());
    
                                           
    
                                       }
                                 else
    
                                    {
    
                                        ps.setInt(c, Integer.parseInt(tm.getValueAt(r, c-1).toString()));
    
                                    }
    
     
    
                                }
    
                                   
    int k=ps.executeUpdate();
    System.out.println("Created Prepared Statement "+k);
                               
    
                            }
                       
                           conn.close();
                           ps.close();
                        }
    
                         
    
                         catch(Exception ex)
    
                        {
    
                            ex.printStackTrace();
    
                        }
    
                     }
    
           if(e.getSource()== btnDelete){
           int[] rows=table.getSelectedRows();
       for(int i=0;i<rows.length;i++){
       tabMod.removeRow(rows[i]-i);
       records.remove(rows[i]-i);
           
           
           }
    
                }
    
        }
       }
      // private Vector getColumnNames()
    
     //  {
    
       // Vector<String> columnNames = new Vector<String>();
    
     
    
      //  for (int i = 0; i < table.getColumnCount(); i++)
    
       //   columnNames.add(table.getColumnName(i));
    //
     
    
       // return columnNames;
    
     // }
        public Object[][] getTableData (JTable table)
    
      {
    
           int nRow = tabMod.getRowCount(), nCol = tabMod.getColumnCount();
    
           Object[][] tableData = new Object[nRow][nCol];
    
           for (int i = 0 ; i < nRow ; i++)
    
             for (int j = 0 ; j < nCol ; j++)
    
              { 
    
                tableData[i][j] = tabMod.getValueAt(i,j);
    
                 System.out.println(tableData[i][j]);
    
              }
    
       return tableData;
    
      }
    
     public JMenuBar createMenuBar()
     {
      //create instance of the menu
      JMenuBar mnuBar = new JMenuBar();
      setJMenuBar(mnuBar);
    
      //construct and populate the File menu
      JMenu mnuFile = new JMenu("File", true);
       mnuFile.setMnemonic(KeyEvent.VK_F);
       mnuFile.setDisplayedMnemonicIndex(0);
       mnuBar.add(mnuFile);
     JMenuItem mnuOpen = new JMenu("Open");
       mnuOpen.setMnemonic(KeyEvent.VK_R);
       mnuOpen.setDisplayedMnemonicIndex(0);
       mnuFile.add(mnuOpen);
       mnuOpen.setActionCommand("Open");
      JMenuItem mnuFileExit = new JMenuItem("Exit");
       mnuFileExit.setMnemonic(KeyEvent.VK_X);
       mnuFileExit.setDisplayedMnemonicIndex(0);
       mnuFile.add(mnuFileExit);
       mnuFileExit.setActionCommand("Exit");
       
      
    
    
      mnuFileExit.addActionListener(new ActionListener(){
    public  void actionPerformed(ActionEvent ae){
    System.exit(0);
    
    }
    
    });
    mnuOpen.addActionListener(new ActionListener(){
    public  void actionPerformed(ActionEvent ae){
      
       
    
    }
    
    });
      return mnuBar;
     }
       
       public void sortRecords(){
       Collections.sort(records);
       loadProductsIntoTable();
       
       }
       public void resetRecords(){
           tabMod=null;
         records=null;
    
    
       }
     
    
       public void DVD_ListaddRecords(){
       String [] row= new String[5];
       DVD newProd= new DVD(Integer.parseInt(txtCost.getText()),txtid.getText(),txtName.getText(),
               txtType.getText(),txtDesc.getText());
       records.add(newProd);
       row[0]= newProd.getID();
       row[1]=newProd.getName();
       row[2]=Integer.toString(newProd.getCost());
       row[3]=newProd.getType();
       row[4]=newProd.getNote();
       
       tabMod.addRow(row);
     
       }
       
    
    
    
       public void loadProductsIntoTable(){
       tabMod.setRowCount(0);
       String []row= new String[5];
       for (Iterator i=records.iterator();i.hasNext();){
       DVD temp = (DVD)i.next();
        row[0]=temp.getID();
       row[1]=temp.getName();
       row[2]=Integer.toString(temp.getCost());
       row[3]=temp.getType();
       row[4]=temp.getNote();
      
               
       tabMod.addRow(row);
       
           }
       }
    
        public static void main(String[] a) {
           MyCoursework cs= new MyCoursework();
           cs.setJMenuBar(cs.createMenuBar());
           cs.addWindowListener(new WindowAdapter(){
               public void windowClosing(WindowEvent e){
               System.exit(0);
               }
            }); 
         
    
        cs.pack();
        cs.setVisible(true);
          
        }
        
        
    
    
    }
    Last edited by Fubarable; 11-18-2011 at 03:36 PM.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: unable to add JTable data into microsoft access!!! please help me with the code!

    Moderator action: post "approved" and code tags added.

    To the original poster: you may wish to add a paragraph or two telling us more details about your exact problem.

  3. #3
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,233
    Rep Power
    6

    Default Re: unable to add JTable data into microsoft access!!! please help me with the code!

    Your question is about a JTable. What is all the other code posted for? We don't have time to read and understand that code.

    When providing more information as requested by Fubarable edit your original posting to post a proper Short, Self Contained, Correct Example
    Fubarable likes this.

  4. #4
    cute is offline Member
    Join Date
    Nov 2011
    Posts
    6
    Rep Power
    0

    Default Re: unable to add JTable data into microsoft access!!! please help me with the code!

    run:
    Databse Connected
    rows:2columns:5
    java.lang.NumberFormatException: For input string: "fdsgf"
    at java.lang.NumberFormatException.forInputString(Num berFormatException.java:48)
    at java.lang.Integer.parseInt(Integer.java:449)
    at java.lang.Integer.parseInt(Integer.java:499)
    at MyCoursework$Listener.actionPerformed(MyCoursework .java:207)
    at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.jav a:6263)
    at javax.swing.JComponent.processMouseEvent(JComponen t.java:3267)
    at java.awt.Component.processEvent(Component.java:602 8)
    at java.awt.Container.processEvent(Container.java:204 1)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4630)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2099)
    at java.awt.Component.dispatchEvent(Component.java:44 60)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4574)
    at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4238)
    at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4168)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2085)
    at java.awt.Window.dispatchEventImpl(Window.java:2478 )
    at java.awt.Component.dispatchEvent(Component.java:44 60)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 599)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:122)


    im getting this error

  5. #5
    cute is offline Member
    Join Date
    Nov 2011
    Posts
    6
    Rep Power
    0

    Default Re: unable to add JTable data into microsoft access!!! please help me with the code!

    my problem is i can the data into JTable but when i press save btn to save into microsoft access im getting number format exception. im not sure where i went wrong this is my code connecting to microsoft access through save btn:

    class Listener implements ActionListener

    {

    @Override
    public void actionPerformed(ActionEvent e)

    {

    if(e.getSource() == btnSave)

    {

    try

    {

    // Establish a connection

    conn = DriverManager.getConnection

    ("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=dvdrecords.mdb;");

    System.out.println("Databse Connected");



    s = conn.createStatement();

    String sql = "INSERT INTO dvdlist VALUES(?,?,?,?,?);";

    PreparedStatement ps = conn.prepareStatement(sql);


    ps.setString(1,txtid.getText());
    ps.setString(2,txtName.getText());
    ps.setString(3,txtCost.getText());
    ps.setString(4,txtType.getText());
    ps.setString(5,txtDesc.getText());




    TableModel tm = table.getModel();



    int nRow = tm.getRowCount(), nCol = tm.getColumnCount();

    System.out.println( " rows:" + nRow + "columns:" + nCol);

    for(int r = 0;r < nRow; r++)

    {

    for(int c = 1;c <= nCol;c++)
    {

    // ps.setObject(c, tm.getValueAt(r, (nCol-1)));

    if (c == 1 )

    {

    ps.setString(c, tm.getValueAt(r, nCol-1).toString());



    }
    else

    {

    ps.setInt(c, Integer.parseInt(tm.getValueAt(r, c-1).toString()));

    }



    }


    int k=ps.executeUpdate();
    System.out.println("Created Prepared Statement "+k);


    }

    conn.close();
    ps.close();
    }



    catch(Exception ex)

    {

    ex.printStackTrace();

    }

    }

  6. #6
    cute is offline Member
    Join Date
    Nov 2011
    Posts
    6
    Rep Power
    0

    Default Re: unable to add JTable data into microsoft access!!! please help me with the code!

    my problem is here, I am able to add data into JTable but when i click save btn,it shows some error above im not sure which part i went wrong pls help me!
    this is my code:

    class Listener implements ActionListener

    {

    @Override
    public void actionPerformed(ActionEvent e)

    {

    if(e.getSource() == btnSave)

    {

    try

    {

    // Establish a connection

    conn = DriverManager.getConnection

    ("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=dvdrecords.mdb;");

    System.out.println("Databse Connected");



    s = conn.createStatement();

    String sql = "INSERT INTO dvdlist VALUES(?,?,?,?,?);";

    PreparedStatement ps = conn.prepareStatement(sql);


    ps.setString(1,txtid.getText());
    ps.setString(2,txtName.getText());
    ps.setString(3,txtCost.getText());
    ps.setString(4,txtType.getText());
    ps.setString(5,txtDesc.getText());




    TableModel tm = table.getModel();



    int nRow = tm.getRowCount(), nCol = tm.getColumnCount();

    System.out.println( " rows:" + nRow + "columns:" + nCol);

    for(int r = 0;r < nRow; r++)

    {

    for(int c = 1;c <= nCol;c++)
    {

    // ps.setObject(c, tm.getValueAt(r, (nCol-1)));

    if (c == 1 )

    {

    ps.setString(c, tm.getValueAt(r, nCol-1).toString());



    }
    else

    {

    ps.setInt(c, Integer.parseInt(tm.getValueAt(r, c-1).toString()));

    }



    }


    int k=ps.executeUpdate();
    System.out.println("Created Prepared Statement "+k);


    }

    conn.close();
    ps.close();
    }



    catch(Exception ex)

    {

    ex.printStackTrace();

    }

    }

  7. #7
    cute is offline Member
    Join Date
    Nov 2011
    Posts
    6
    Rep Power
    0

    Default Re: unable to add JTable data into microsoft access!!! please help me with the code!

    my problem is here, I am able to add data into JTable but when i click save btn,it shows some error above im not sure which part i went wrong pls help me!
    this is my code:

    class Listener implements ActionListener

    {

    @Override
    public void actionPerformed(ActionEvent e)

    {

    if(e.getSource() == btnSave)

    {

    try

    {

    // Establish a connection

    conn = DriverManager.getConnection

    ("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=dvdrecords.mdb;");

    System.out.println("Databse Connected");



    s = conn.createStatement();

    String sql = "INSERT INTO dvdlist VALUES(?,?,?,?,?);";

    PreparedStatement ps = conn.prepareStatement(sql);


    ps.setString(1,txtid.getText());
    ps.setString(2,txtName.getText());
    ps.setString(3,txtCost.getText());
    ps.setString(4,txtType.getText());
    ps.setString(5,txtDesc.getText());




    TableModel tm = table.getModel();



    int nRow = tm.getRowCount(), nCol = tm.getColumnCount();

    System.out.println( " rows:" + nRow + "columns:" + nCol);

    for(int r = 0;r < nRow; r++)

    {

    for(int c = 1;c <= nCol;c++)
    {

    // ps.setObject(c, tm.getValueAt(r, (nCol-1)));

    if (c == 1 )

    {

    ps.setString(c, tm.getValueAt(r, nCol-1).toString());



    }
    else

    {

    ps.setInt(c, Integer.parseInt(tm.getValueAt(r, c-1).toString()));

    }



    }


    int k=ps.executeUpdate();
    System.out.println("Created Prepared Statement "+k);


    }

    conn.close();
    ps.close();
    }



    catch(Exception ex)

    {

    ex.printStackTrace();

    }

    }

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default Re: unable to add JTable data into microsoft access!!! please help me with the code!

    You're attempting to parse the String "fdsgf" into an int...which it clearly isn't.

    Why you are doing that is something only you can figure out.

  9. #9
    cute is offline Member
    Join Date
    Nov 2011
    Posts
    6
    Rep Power
    0

    Default Re: unable to add JTable data into microsoft access!!! please help me with the code!

    i got it! finally is done!

Similar Threads

  1. Replies: 5
    Last Post: 09-11-2011, 05:13 AM
  2. Replies: 3
    Last Post: 08-15-2011, 10:16 AM
  3. face problem to read data from microsoft access
    By chyeeqi in forum New To Java
    Replies: 7
    Last Post: 08-21-2009, 01:08 PM
  4. Replies: 1
    Last Post: 08-07-2007, 07:51 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •