Search code examples
javadatabaseeclipseucanaccess

Adding row in jtable and database using Java


I have a problem with my code and it has no error log so I can't see the problem . . .

Current Problem:
Mainclass() is where the main frame is. . . Clicking ADD will open 
AddBroker() and clicking ADD in AddBroker() will update databse and jtable 
in MainClass(). Database can now be updated but the jtable in MainClass() won't
change until you open it again

This is my main class (other codes were redacted to focus on problem)

public class MainClass extends JFrame {
  JButton button_17 = new JButton("ADD");
  button_17.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        //to call class AddBroker()
        AddBroker ab = new AddBroker();
        ab.setVisible(true);

        }
    });}

Then this is the class for AddBroker(). . .

public class AddBroker extends JFrame {
  JButton btnAdd = new JButton("ADD");
  final Object[] addBrokerrow = new Object[3];
  btnAdd.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) { 

            ButtonCon bcd = new ButtonCon();
            DriverTableCon dtcd = new DriverTableCon(); //this is just jtable
            MainClass mcd = new MainClass();
            String a = brokerBroker.getText();
            String b = addBroker.getText();
            String c = tinBroker.getText();

            addBrokerrow[0] = a;
            addBrokerrow[1] = b;
            addBrokerrow[2] = c;

            dtcd.modelBroker.addRow(addBrokerrow);
            bcd.addBrokerCon(a,b,c);
        }
    });}

And ButtonCon() is where the adding of data is

public class ButtonCon {
 Connection con;
 Statement st;
 ResultSet rs;
 StringBuffer results;
 String url = "jdbc:ucanaccess://C://DATABASE//NTD.accdb";
 public void addBrokerCon(String broker, String add, String tin) {
    try {
        con = DriverManager.getConnection(url);

        String sql = "INSERT INTO brokerT (Broker, Address, Tin_No) VALUES     (?,?,?)";

        ps = con.prepareStatement(sql);

        ps.setString(1, broker);
        ps.setString(2, add);
        ps.setString(3, tin);

        ps.executeUpdate();
        ps.close();
        con.close();

    }

    catch (Exception e) {
            System.out.print(e.toString());
    }
} }

There is no error so I have no idea what is wrong here. Any input would be appreciated :)

So it's been a week and what I did try to solve the problem and what I did is add a "Refresh" button that loads the table again.


Solution

  • You fogot about ps.executeUpdate(); between ps.setString(3, tin); and ps.close();.

    And remove all with st it is not necessary.