当前位置: 首页 > 面试题库 >

我在使用JDBC连接池吗?

左丘昕
2023-03-14
问题内容

我试图确定我是否实际上正在使用JDBC连接池。经过研究后,实现似乎太容易了。实际上比常规连接容易,所以我想验证一下。

这是我的连接类:

public class DatabaseConnection {

Connection conn = null;

public Connection getConnection() {

    BasicDataSource bds = new BasicDataSource();
    bds.setDriverClassName("com.mysql.jdbc.Driver");
    bds.setUrl("jdbc:mysql://localhost:3306/data");
    bds.setUsername("USERNAME");
    bds.setPassword("PASSWORD");

    try{
        System.out.println("Attempting Database Connection");
        conn = bds.getConnection();
        System.out.println("Connected Successfully");
    }catch(SQLException e){
        System.out.println("Caught SQL Exception: " + e);
    }
    return conn;
}

public void closeConnection() throws SQLException {
    conn.close();
}

}

这是真正的连接池吗?我在另一个类中使用连接是这样的:

        //Check data against database.
    DatabaseConnection dbConn = new DatabaseConnection();
    Connection conn;
    ResultSet rs;
    PreparedStatement prepStmt;

    //Query database and check username/pass against table.
    try{
        conn = dbConn.getConnection();
        String sql = "SELECT * FROM users WHERE username=? AND password=?";
        prepStmt = conn.prepareStatement(sql);
        prepStmt.setString(1, user.getUsername());
        prepStmt.setString(2, user.getPassword());
        rs = prepStmt.executeQuery();

        if(rs.next()){ //Found Match.
            do{
                out.println("UserName = " + rs.getObject("username") + " Password = " + rs.getObject("password"));
                out.println("<br>");
            } while(rs.next());
        } else {
            out.println("Sorry, you are not in my database."); //No Match.
        }

        dbConn.closeConnection(); //Close db connection.

    }catch(SQLException e){
        System.out.println("Caught SQL Exception: " + e);
    }

问题答案:

假设它BasicDataSource是来自DBCP的,那么是的,您正在使用连接池。但是,您将在每次获取连接时重新创建另一个连接池。您并不是真正地在同一个池中合并连接。您只需在应用程序启动时创建一次连接池,并从中获取每个连接。您也不应将连接保留为实例变量。您还应该关闭连接,语句和结果集,以确保在异常情况下也正确关闭了资源。Java
7的try-with- resources语句对此很有帮助,它会在try块完成后自动关闭资源。

这是一个小的重写:

public final class Database {

    private static final BasicDataSource dataSource = new BasicDataSource();

    static {
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/data");
        dataSource.setUsername("USERNAME");
        dataSource.setPassword("PASSWORD");
    }

    private Database() {
        //
    }

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

}

(如有必要,可以将其重构为抽象工厂以提高可插入性)

private static final String SQL_EXIST = "SELECT * FROM users WHERE username=? AND password=?";

public boolean exist(User user) throws SQLException {
    boolean exist = false;

    try (
        Connection connection = Database.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL_EXIST);
    ) {
        statement.setString(1, user.getUsername());
        statement.setString(2, user.getPassword());

        try (ResultSet resultSet = preparedStatement.executeQuery()) {
            exist = resultSet.next();
        }
    }

    return exist;
}

使用方法如下:

try {
    if (!userDAO.exist(username, password)) {
        request.setAttribute("message", "Unknown login. Try again.");
        request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
    } else {
        request.getSession().setAttribute("user", username);
        response.sendRedirect("userhome");
    }
} catch (SQLException e) {
    throw new ServletException("DB error", e);
}

但是,在实际的Java
EE环境中,您应该将的创建委托DataSource给容器/应用程序服务器,并从JNDI获取它。如果是Tomcat,请另参见本文档的示例:http : //tomcat.apache.org/tomcat-6.0-doc/jndi-resources-
howto.html



 类似资料:
  • 我正在尝试使用google cloud sql和云endpoint开发一个应用程序,从google cloud sql文档中我发现google loud sql的连接器不提供任何连接池机制,我尝试在线搜索以获得任何可能的教程或文档,这些教程或文档提供了池机制,但没有结果,google文档只是指出,您应该在finally块中关闭连接,而不需要任何连接池配置。我还遇到了BoneCp、TomcatDbC

  • Tomcat在使用后不释放连接的原因可能是什么? 这是我的配置

  • 问题内容: 我们使用JDBC的标准代码部分是… 问题1:使用连接池时,是否应该在最后关闭连接?如果是这样,合并的目的就不会丢失吗?如果不是,那么DataSource如何知道何时释放Connection的特定实例并可以重用?我对此感到有些困惑,任何指针都表示赞赏。 问题2:以下方法是否接近标准?看起来像是尝试从池中获取连接,并且如果无法建立DataSource,请使用老式的DriverManager

  • 前几天我经历了应用程序的中断,我需要了解以后如何避免这种情况。 我们有一个运行在Tomcat7上的基于Java的web应用程序。应用程序连接到几个不同的数据源,包括Oracle数据库。 下面是我对连接验证的理解。 连接在空闲时(testWhileIdle=false)、借用时(testOnBorrow=false)、返回时(testOnReturn=false) 由于timeBetweenEvic

  • 我使用作为我的数据源实现,我的代码获取连接并关闭连接,如下所示: 当我完成连接工作时,我将关闭它 我的问题是:确实是关闭的,所以当连接像一样关闭时,数据源是如何工作的。我听说datasource connection close并不是真正的close,只是release,但我在datasource类中找不到release API。我想知道datasource如何管理数据库连接的创建、关闭和释放。

  • 我们有一个spring-boot应用程序,它使用嵌入式tomcat进行部署,并使用MySQL后端的默认tomcat-jdbc连接池,而没有为MySQL或tomcat端定制。 该应用程序有一些调度程序,它们主要在一天中的特定时间运行,即在昨天的最后一次cron运行和今天的第一次cron运行之间,有超过9个小时的间隙。然而,无论何时cron在早期运行,它都从未遇到过空闲连接问题。 现在我们看到一条错误