简体   繁体   English

JAVA JDBC重用连接

[英]JAVA JDBC reusing connections

I have a Java program in which I am doing some JDBC for select queries. 我有一个Java程序,我在其中为选择查询做一些JDBC。 Will it be advisable to call testDataBase() each time which inturns calls DBConnection() each time or I should reuse one connection for all the queries. 每次inturns调用DBConnection()时我都应该调用testDataBase(),或者我应该为所有查询重用一个连接。 Thanks in advance. 提前致谢。

private  void testDataBase(String query){
    Connection con = DBConnection();
    Statement st = null;
    ResultSet rs = null;

    try {
        st = con.createStatement();
        rs = st.executeQuery(query);
        boolean flag = true;
        while (rs.next()) {
            String resultString = "";
            for(int i = 1; i <=rs.getMetaData().getColumnCount();i++){
                resultString=resultString+" "+  rs.getString(i);
            }
            System.out.println(resultString);
        }
    } catch (SQLException e) {
        e.printStackTrace();

    } finally {
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}               



private  Connection DBConnection() {
    final String method_name =  "DBConnection";
    Connection conn = null;
    try{
      Class.forName(driver).newInstance();
      conn = java.sql.DriverManager.getConnection(url,userName,password);

    }catch (ClassNotFoundException e) {
        System.out.println(e.getMessage());
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    return conn;
}

Opening a DB connection is an expensive operation in terms of perfofmance. 在perfofmance方面,打开DB连接是一项昂贵的操作。 You should use a ConnectionPool for sharing connections among different requests. 您应该使用ConnectionPool在不同请求之间共享连接。

数据库连接是长时间运行的,应该重复使用,除非您的查询率非常低。

Connections are not thread safe, so sharing them across requests is not a good idea. 连接不是线程安全的,因此跨请求共享它们不是一个好主意。

A better idea is to pool connections and keep their scope as narrow as possible: check the connection out of the pool, use it, close it in transaction scope. 更好的想法是池连接并尽可能缩小其范围:检查池外的连接,使用它,在事务范围内关闭它。

Getting a database connection is quite an expensive operation, so it is advisable to re-use a connection if possible. 获取数据库连接是一项非常昂贵的操作,因此建议尽可能重用连接。 Consider also using connection pooling, which will maintain a number of connections for you, so you can just grab one from the pool when needed. 还要考虑使用连接池,它将为您维护许多连接,因此您可以在需要时从池中获取一个连接。 The method shown above might not need to change, it depends on the DBConnection() method you call. 上面显示的方法可能不需要更改,它取决于您调用的DBConnection()方法。

I completely agree with @Amir Kost, in terms of performances, opening a DB connection in one of the slowest operation that you can do, and if you have restrictive real time constraints it could be a big issue. 我完全赞同@Amir Kost,在性能方面,在你可以做的最慢的操作之一中打开数据库连接,如果你有限制性的实时限制,那么这可能是个大问题。 I do not know if you are using a framework or not, but a good practice is to publish a bean which wrap a pool of connection and every time that you need to interact directly with the db, you get the current open connection (which usually corresponds to a so called "session"). 我不知道你是否使用框架,但一个好的做法是发布一个包装连接池的bean,每次你需要直接与db交互时,你得到当前的开放连接(通常是对应于所谓的“会话”)。 I suggest to you, (even if you are not using any framework) to reproduce this technicality. 我建议你(即使你没有使用任何框架)来重现这种技术性。

If you want only one instance of Connection, you can make use of the Singleton pattern, you can consider : 如果只想要一个Connection实例,可以使用Singleton模式,可以考虑:

public class Connector {

private static final String URL = "jdbc:mysql://localhost/";
private static final String LOGIN = "root";
private static final String PASSWORD = "azerty";
private static final String DBNAME = "videotheque";
private static Connector connector;
private static Connection connection;

private Connector() {
}

public synchronized static Connector getInstance() {
    if (connector == null) {
        connector = new Connector();
    }
    return connector;
}

public static Connection getConnection() {
    if (connection == null) {
        Connection c = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            c = DriverManager.getConnection(URL + DBNAME, LOGIN, PASSWORD);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return c;
    }
    return connection;
}

} }

And then, you can call : Connector.getInstance().getConnection() 然后,您可以调用: Connector.getInstance().getConnection()

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

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