Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display data from MS Access database in a JTable?

I'm currently developing a program in the NetBeans IDE. I have created a nice GUI and I have created my MS Access Database. I am having trouble in displaying MS Access data in JTable. I would like to avoid the use of vectors, as shown in most of the tutorials, I found on the internet, as I am still in High school and this knowledge is beyond me.

Any pointers in the right direction will be immensely appreciated!

Here is my code:

 String[] columnNames = {"First Name",
                              "Last Name",
                               "Category",
                               "Amount"
                               };
  Object[] row =new Object[4];
  JLabel lbl=new JLabel("Add New Property");
  lbl.setBounds(100,200,200,100);
  lbl.setVisible(true);
  invntryfrm.add(lbl);
  //invntryfrm.setVisible(true);
  JPanel panel=new JPanel();
  panel.setBounds(20,200,680,100);
  panel.setBackground(Color.WHITE);
  invntrybck.add(panel);
  DefaultTableModel model=new DefaultTableModel();
  model.setColumnIdentifiers(columnNames);
  JTable tabel=new JTable();
  tabel.setBounds(100,20,700,400);
  tabel.setBackground(Color.DARK_GRAY);
  tabel.setForeground(Color.WHITE);
  tabel.setModel(model);
  tabel.setPreferredScrollableViewportSize(new Dimension(500,50));
  tabel.setFillsViewportHeight(true);
  JScrollPane pane=new JScrollPane(tabel);
  panel.add(pane);
  try{
  Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\MUHAMMAD SHAHAB\\real estate.accdb");
  String sql="select Username,Password,Country,City from simba";
  PreparedStatement pst=conn.prepareStatement(sql);
  ResultSet rs=pst.executeQuery();

   }
   catch(Exception ex)
   {
       JOptionPane.showMessageDialog(null, ex);
   }
like image 807
Mcolo Avatar asked Feb 07 '23 00:02

Mcolo


1 Answers

(1).First add rs2Xml.jar in your library folder and then do the following change in your code:

 Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\MUHAMMAD SHAHAB\\real estate.accdb");
                               String sql="select Username,Password,Country,City from simba";
                               PreparedStatement pst=conn.prepareStatement(sql);
                               ResultSet rs=pst.executeQuery();
                               tabel.setModel(DbUtils.resultSetToTableModel(rs)); 

I hope this will work fine for you.

like image 171
Shahab Khan Avatar answered Feb 08 '23 15:02

Shahab Khan