我们有一个实用程序类,用于打开和断开Derby DB连接
数据库存储在Windows 7计算机的C盘上的文件夹中
该应用程序是使用JavaFX 8编写的
我们不使用事务
在使用实用程序类之前,我们将打开并断开与每个CRUD函数rs.close()和con.close()的连接
我们的问题有两个部分
在以下情况下将触发conn.close()
我们将发布Utility Class和Delete函数的代码
当应用程序关闭时,我们还在主类中使用下面的代码来关闭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);
}和Delete函数
@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");
}发布于 2019-08-27 05:31:11
使用连接池访问数据库
我建议使用连接池,而不是编写自己的连接逻辑,例如,请参阅Baeldung Hikari Tutorial。你可以这样使用它:
DataSource连接的示例包装类(从上面的Baeldung Hikari链接复制):
public class DataSource {
private static HikariConfig config = new HikariConfig();
private static HikariDataSource ds;
static {
config.setJdbcUrl( "jdbc_url" );
config.setUsername( "database_username" );
config.setPassword( "database_password" );
config.addDataSourceProperty( "cachePrepStmts" , "true" );
config.addDataSourceProperty( "prepStmtCacheSize" , "250" );
config.addDataSourceProperty( "prepStmtCacheSqlLimit" , "2048" );
ds = new HikariDataSource( config );
}
private DataSource() {}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}使用Hikari连接池并使用Java的try with resources结构自动关闭连接的示例数据库调用(从上面的Baeldung Hikari链接复制):
public static List<Employee> fetchData() throws SQLException {
String SQL_QUERY = "select * from emp";
List<Employee> employees = null;
try (Connection con = DataSource.getConnection();
PreparedStatement pst = con.prepareStatement( SQL_QUERY );
ResultSet rs = pst.executeQuery();) {
employees = new ArrayList<>();
Employee employee;
while ( rs.next() ) {
employee = new Employee();
employee.setEmpNo( rs.getInt( "empno" ) );
employee.setEname( rs.getString( "ename" ) );
employee.setJob( rs.getString( "job" ) );
employee.setMgr( rs.getInt( "mgr" ) );
employee.setHiredate( rs.getDate( "hiredate" ) );
employee.setSal( rs.getInt( "sal" ) );
employee.setComm( rs.getInt( "comm" ) );
employee.setDeptno( rs.getInt( "deptno" ) );
employees.add( employee );
}
}
return employees;
} 有关更多信息,请阅读Baeldung教程和Hikari站点文档:
不使用连接池的数据库访问
现在,您不需要使用连接池来完成此操作,您可以为每个数据库调用打开和关闭连接,但是出于性能原因,我建议您使用连接池,这样您就不会试图重新发明轮子,最终得到的是方形而不是圆形。
我没有尝试调试或检查您的问题中的连接实用程序类,但是,如果您无论如何都要将其替换为连接池,则没有理由这样做。
在没有连接池的情况下从JavaFX访问数据库的示例代码:
使用Task based sample for db access.的
一些示例代码是为了演示特定目的而编写的,例如访问数据库和将数据从给定表反馈到UI,而不是作为通用的数据库实用程序。对于使用许多数据库查询的应用程序的健壮实现,最好使用连接池或专用数据库连接管理器类(如您在问题中所述)。
https://stackoverflow.com/questions/57664889
复制相似问题