Best way to manage database connection for a Java servlet

前端 未结 9 498
南方客
南方客 2020-12-02 10:28

What is the best way to manage a database connection in a Java servlet?

Currently, I simply open a connection in the init() function, and then close it

9条回答
  •  庸人自扰
    2020-12-02 10:44

    I'd use Commons DBCP. It's an Apache project that manages the connection pool for you.

    You'd just get your connection in your doGet or doPost run your query and then close the connection in a finally block. (con.close() just returns it to the pool, it doesn't actually close it).

    DBCP can manage connection timeouts and recover from them. The way you are currently doing things if your database goes down for any period of time you'll have to restart your application.

提交回复
热议问题