简体   繁体   English

静态最终在Java中阻塞

[英]Static finally block in Java

I have a class that uses a static initialization block to set up a connection to a database. 我有一个类使用static初始化块来建立与数据库的连接。 The class has many public static methods that query the db. 该类有许多查询db的public static方法。 I would like to properly close this connection in a static block that executes just before the program terminates, kind of like a finally block in a try/catch . 我想在程序终止之前执行的static块中正确关闭此连接,有点像try/catchfinally块。 I am almost certain that something like this does not exist in Java. 我几乎可以肯定Java中不存在这样的东西。 Is my best option to open and close the connection with each query? 我是打开和关闭每个查询连接的最佳选择吗?

Have a look at this : Running a method when closing the program? 看看这个: 关闭程序时运行方法?

You could try writing the code to close connection in this method. 您可以尝试编写代码以在此方法中关闭连接。

public static void main(String[] args) {
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            //code to close connection
        }
    }, "Shutdown-thread"));
}

Opening and closing the connection for every query will cause an additional overhead on system making the application slow. 为每个查询打开和关闭连接将导致系统额外开销使应用程序变慢。

You could surround the final query of your DB program with try catch blocks instead and release the connection in the finally clause (for the last query of your program). 您可以使用try catch块来代替数据库程序最终查询,并在finally子句中释放连接(用于程序的最后一次查询)。

NOTE: If the JVM terminates before the main thread finishes execution, ie System.exit() executes, the subsequent code and the finally block won't be executed. 注意:如果JVM在主线程完成执行之前终止,即执行System.exit(),则不会执行后续代码和finally块。

public class JdbcDBManager {
private Connection connection = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;

public JdbcDBManager(String url, String user, String pass) throws ClassNotFoundException, SQLException {
    Class.forName("org.gjt.mm.mysql.Driver");
    this.connection = DriverManager.getConnection(url, user, pass);
}

public void close() {
    try {if (this.preparedStatement != null)this.preparedStatement.close();} catch (Exception e) {e.printStackTrace();}
    try {if (this.resultSet != null)this.resultSet.close();} catch (Exception e) {e.printStackTrace();}
    try {if (this.connection != null)this.connection.close();} catch (Exception e) {e.printStackTrace();}
}
public void customerInsert(Customer customer) {
    try {
        String query = "INSERT INTO customer(email,product) VALUES(?,?,?,?,?)";
        this.preparedStatement = this.connection.prepareStatement(query);
        this.preparedStatement.setString(1, customer.getEmail());
        this.preparedStatement.setString(3, customer.getProduct());
    } catch (Exception e) { e.printStackTrace();}
}}

You can create an object for each Database and when you are finally done processing close it. 您可以为每个数据库创建一个对象,并在最终完成处理时关闭它。

public class test {

public static void process() throws ClassNotFoundException, SQLException {
    JdbcDBManager customerDB = new JdbcDBManager(JdbcURL.URL, JdbcURL.USER, JdbcURL.PASS);
    try {
        customerDB.insertCustomer(Customer customer);
        doSomething(customerDB); // Pass db object as a parameter
    } finally { customerDB.close();} // close it when you are finally done
}
doSomething(JdbcDBManager customerDB){
     ---------------------------
     --process info in db-------
} }

This way you open connection for one time and close when process are finally finished 这样,您可以打开一次连接,并在最终完成流程时关闭

Is my best option to open and close the connection with each query? 我是打开和关闭每个查询连接的最佳选择吗? Ans : NO 答:没有

I would suggest you to follow: 我建议你遵循:

Singleton Class for opening the connection, something like this : 用于打开连接的Singleton Class ,如下所示:

public class connectDB {
static Connection conn = null;

public static Connection getConnection(){
    if (conn != null) return conn;
    String connString = "DATABASE ACCESS URL HERE";
    return getConnection(connString);
}

private static Connection getConnection(String conString){
    try{
        Class.forName("LOAD DRIVER HERE");
        String uname = "DB USERNAME";
        String pass = "DB PASSWORD";
        conn = DriverManager.getConnection(conString, uname, pass);  
    }
    catch(Exception e){
        //Handle Exceptions
        e.printStackTrace(); //<--Retrieves the error/Exception for you
    }
    return conn;
}
}

And close the connection with something like : 并通过以下方式关闭连接:

public static void closeConnection(Connection conn) {
try {
    conn.close();
}
catch (SQLException e) {
    //Handle Exception Here
}
}

Just call conn = connectDB.getConnection() for connection and the other one for closing, preferable in a finally 只需调用conn = connectDB.getConnection()进行连接,另一个用于关闭,最好是在finally

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM