insert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
String sql1 = "Insert into supplier (SupplierID, CompanyName,PhoneNumber) values (?,?,?)";
Connection conn = null;
conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Jela\\Desktop\\repo\\Master\\Working\\database.db");
PreparedStatement pst = conn.prepareStatement(sql1);
pst.setString(1, supplierID.getText());
pst.setString(2, companyname.getText());
pst.setString(3, contactnumber.getText());
pst.execute();
System.out.println("data inserted");
conn.close();
}catch(Exception e2){
System.out.println(e2);
}
try{
String sql2 = "Select * FROM supplier";
Connection conn1 = null;
conn1 = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Jela\\Desktop\\repo\\Master\\Working\\database.db");
PreparedStatement pst = conn1.prepareStatement(sql2);
ResultSet rs = pst.executeQuery();
DefaultTableModel model1 = new DefaultTableModel(data, columnNames);
table.setModel(model1);
conn1.close();
}catch(Exception e3){
System.out.println(e3);
}
}
});
我有一个插入按钮,当我单击插入按钮时,数据应该添加到数据库中。但是,只有在我关闭程序并重新开始时才会显示数据。我启动了更新代码,但它没有更新。任何人都可以给我一些关于如何在JTable中更新数据库的提示。
提前致谢
答案 0 :(得分:0)
在关闭您的连接和preparedStatement的finally
之后添加catch
块。
...
} finally {
if (pst!= null) {
pst.close();
}
if (conn != null) {
conn .close();
}
关闭资源的另一种方法是使用try-with-resources语句
try (Connection conn = DriverManager.getConnection(myConnectionURL);
PreparedStatement pst = conn.prepareStatement(sql1);)