简体   繁体   English

Java DB Connection Manager最佳实践

[英]Java DB Connection Manager Best Practice

I have a connection manager code as follows: 我有一个连接管理器代码,如下所示:

public class ConnectionManager {

    private final String driverName = "com.mysql.jdbc.Driver";
    private final String connectionUrl = "jdbc:mysql://localhost:3306/student";
    private final String userName = "root";
    private final String userPass = "root";

    private Connection con = null;

    public ConnectionManager() {
        try {
            Class.forName(driverName);
        } catch (ClassNotFoundException e) {
            System.out.println(e.toString());
        }
    }

    public Connection createConnection() {
        try {
            con = DriverManager.getConnection(connectionUrl, userName, userPass);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    public void closeConnection() {
        try {
            this.con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

} }

How can I improve this? 我该如何改善? I am thinking the following improvement: 我在想以下改进:

  1. ) create a connection.properties. )创建一个connection.properties。 What is the best way to implement this? 实现此目的的最佳方法是什么? Should I put it the call of the property file on a singleton? 我应该把对属性文件的调用放在单例上吗?
  2. ) Make the connection singleton. )使连接单例。

Thank you. 谢谢。

如果是用于实际应用程序,则最好使用像http://commons.apache.org/proper/commons-dbcp/这样的连接池。

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

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