【发布时间】:2019-12-31 01:22:22
【问题描述】:
我们有一个实用程序类,可以打开和断开 Derby DB 连接
数据库存储在 Windows 7 计算机 C 盘上的文件夹中
该应用程序是使用 JavaFX 8 编写的
我们不使用交易
在使用实用程序类之前,我们将使用每个 CRUD 函数 rs.close() con.close() 打开和断开连接
我们的问题有两个部分
1.我们真的需要用每个CRUD函数打开和关闭连接吗?
2、为什么Utility Class没有关闭rs和stmnt?
conn.close() 在
时触发
我们将发布实用程序类和删除功能的代码
我们还在主类中使用以下代码在应用程序关闭时关闭 Derby DB
private void handle(WindowEvent e) throws SQLException {
//Proper CLOSE of connection to DB keeps proper incrementing by 1 as set when the table is created
JDBCUtil.closeConnection(conn);
String conURL = "jdbc:derby:;shutdown=true";
try{
DriverManager.getConnection(conURL);
}catch (SQLException se){
if(!(se.getErrorCode() == 50000) && (se.getSQLState().equals("XJ015")))
System.err.println(se);
}
System.exit(0);
Platform.exit();
}
实用类
公共类 JDBCUtil {
public static Connection conn;
public static Connection getConnection() throws SQLException {
// The URL is specific to the JDBC driver and the database you want to connect
String dbName="InfoDB";
String dbURL = "jdbc:derby:C:/A_DerbyDataBase/DBName/" + dbName + ";create=true";
//String dbURL = "jdbc:derby:DATABASE_NAME;create=true";
// Set the user id and password
//String userId = "app";
//String password = "app";
// Get a connection
conn = DriverManager.getConnection(dbURL);
// Set the auto-commit to false ONLY if you use Transactions
/*conn.setAutoCommit(true);*/
System.out.println("111111111111111111111111111 Get Connection ");
return conn;
}
public static void closeConnection(Connection conn) throws SQLException {
if (conn != null) {
System.out.println("222222222222222222222 conn.close ");
conn.close();
}
}
public static void closeStatement(Statement stmnt) throws SQLException{
if (stmnt != null) {
System.out.println("3333333333333333333333 stmnt.close ");
stmnt.close();
}
}
public static void closeResultSet(ResultSet rs) throws SQLException {
if (rs != null) {
System.out.println("44444444444444444444444 rs.close ");
rs.close();
}
}
/*public static void commit(Connection conn) throws SQLException {
if (conn != null) {
conn.commit();
}
}
public static void rollback(Connection conn) throws SQLException {
if (conn != null) {
conn.rollback();
}
}*/
public static void main(String[] args) throws SQLException {
//conn = JDBCUtil.getConnection();
JDBCUtil.closeConnection(conn);
}
还有删除功能
@FXML
private void onDelete(ActionEvent e) throws SQLException, IOException{
conn = JDBCUtil.getConnection();
String sql = "DELETE FROM infodata WHERE ID = ?";
pstmt = conn.prepareStatement(sql);
int ID = Integer.valueOf(txfID.getText());
pstmt.setInt(1, ID);
pstmt.executeUpdate();
pstmt.close();
JDBCUtil.closeConnection(conn);
ReadFromDB();
btnEdit.setVisible(false);
btnDelete.setVisible(false);
btnCancel.setVisible(false);
btnAdd.setVisible(true);
txfInfo.setText("Record Deleted");
}
【问题讨论】:
-
@kleopatra 为什么你觉得有必要编辑 TAG JavaFX
-
因为不相关,为什么还有;)
-
@kleopatra 很明显,该项目是 JavaFX 8,这对桌面开发人员和遵循 JavaFX 标签的人来说意义重大,所以在我看来,这使它相关你知道 EOF 是什么意思吗?