我正在尝试实现一个简单的 GUI 应用程序来处理数据库记录。它将包含记录视图和编辑它们的可能性。这是我的代码的样子:
class MainPanel extends JPanel {
private CachedRowSet crs;
private List<JTextField> fields = new LinkedList<>();
MainPanel() {
try {
//Fill result set with data
crs = new CachedRowSetImpl();
crs.setUrl("jdbc:postgresql:testdb");
crs.setUsername("username");
crs.setPassword("password");
crs.setCommand("SELECT * FROM products");
crs.execute();
//Create text fields with labels
ResultSetMetaData meta = crs.getMetaData();
for (int a = 1; a <= meta.getColumnCount(); a++) {
JTextField field = new JTextField(10);
add(new JLabel(meta.getColumnLabel(a)));
fields.add(field);
add(field);
}
//Fill fields on startup
crs.next();
updateFields();
//Buttons
JButton nextButton = new JButton("Next");
nextButton.addActionListener(...);
add(nextButton);
JButton prevButton = new JButton("Previous");
prevButton.addActionListener(...);
add(prevButton);
JButton saveButton = new JButton("Save changes");
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
try {
for (int a=0; a<fields.size(); a++) {
crs.updateString(a+1, fields.get(a).getText());
}
crs.acceptChanges();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
});
add(saveButton);
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
private void updateFields() throws SQLException {
for (int a = 0; a < fields.size(); a++) {
fields.get(a).setText(crs.getString(a + 1).trim());
}
}
}
走下一个和上一个工作正常。但是在尝试保存记录时出现异常。堆栈跟踪如下:
org.postgresql.util.PSQLException: Cannot commit when autoCommit is enabled.
at org.postgresql.jdbc2.AbstractJdbc2Connection.commit(AbstractJdbc2Connection.java:705)
at com.sun.rowset.internal.CachedRowSetWriter.commit(CachedRowSetWriter.java:1396)
at com.sun.rowset.CachedRowSetImpl.acceptChanges(CachedRowSetImpl.java:893)
at test.MainPanel$3.actionPerformed(MainPanel.java:85)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
...
如何防止此异常?什么是自动提交?我知道 Connection 类可以选择将其设置为 false,但我不想使用 Connection 类。我想使用 CachedResultSet 完成所有事情。我该如何解决这个问题?