有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数据库连接和关闭的java最佳实践

假设我有一个jsp页面,在加载时需要先加载类别,然后加载产品,我有一个数据库连接类,其中包含listCategories和getProducts函数。我的问题是,我应该在调用的每个函数中连接并关闭db连接,还是连接到jsp页面上方的db,然后在页面关闭时关闭加载的示例代码:

    public class DbConnection {

    private Connection conn = null;
    private PreparedStatement ps = null;
    private ResultSet rs = null;

    private void connect() {

        try {
            DriverManager.registerDriver(new Driver());
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop", "", "");
        } catch (SQLException ex) {
            Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void close() {
        try {
            if (!conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public List<Category> listCategories() {

        connect();
        List<Category> listCategory = new ArrayList<>();
        try {
            ps = conn.prepareStatement("select * from Category where sub_category=0");
            rs = ps.executeQuery();
            while (rs.next()) {
                Category u = new Category(rs.getInt("id"), rs.getString("name"), rs.getInt("sub_category"));
                listCategory.add(u);
            }
            return listCategory;
        } catch (SQLException ex) {
            Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            close();
        }
        return null;
    }

    public List<Products> getProducts() {

        connect();
        List<Products> listProducts = new ArrayList<>();
        try {
            ps = conn.prepareStatement("select * from products");
            rs = ps.executeQuery();
            while (rs.next()) {
                Products p = new Products(rs.getInt("id"), rs.getString("name"));
                listCategory.add(p);
            }
            return listCategory;
        } catch (SQLException ex) {
            Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            close();
        }
        return null;
    }
}

jsp代码示例:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    </head>

    <%for(Category c: dc.listCategories()){%>
    <h1><%=c.getName()%></h1>
    <%}%>

    <%for(Products p: dc.getProducts()){%>
    <h1><%=p.getName()%></h1>
    <%}%>
    <body>
        <h1>Hello World!</h1>
    </body>
</html>

共 (1) 个答案

  1. # 1 楼答案

    最好在开始渲染页面之前打开一次连接,查询所有需要的模型数据,然后关闭连接并开始渲染

    这样:

    • 你只能连接一次
    • 通过为模板提供一个业务投诉,准备好呈现模型,您将进一步将模板逻辑与数据库/业务逻辑分离
    • 在呈现模板时,您不会容易出错(这意味着,在处理这种情况时,您不必关闭连接)
    • 在数据库出错的情况下,您将能够轻松地显示不同的模板(因为当业务状态完全建立时,模板将开始呈现)