Should a database connection stay open all the time or only be opened when needed?

前端 未结 6 1392
天命终不由人
天命终不由人 2020-11-28 11:39

I have a bukkit plugin (minecraft) that requires a connection to the database.

Should a database connection stay open all the time, or be opened and closed when nee

6条回答
  •  心在旅途
    2020-11-28 12:35

    You need to close your connections after each query executions.Sometimes you need to execute multiple queries at the same time because the queries are hanging from each other.Such as "first insert task then assign it to the employees".At this time execute your queries on the same transaction and commit it, if some errors occur then rollback.By default autocommit is disabled in JDBC. Example

    Use connection pooling.If you are developing a webapplication then use App Server connection pooling.App server will use the same pooling for each of your applications so you can control the connection count from the one point.Highly recommend the Apache Tomcat Connection pooling.Example

    As an additional info: Connection, Statement and ResultSet.

    1.If you close connection you don't need close statement or resultset.Both of them will be closed automatically

    2.If you close Statement it will close ResultSet also

    3.if you use try-with-resources like this:

    try (Connection con = ...) {
    } catch (SQLException e) {
    }
    

    it will close the connection automatically.Because try-with-resources require autoclosable objects and Connection is autocloseable.You can see the details about try-with-resources here

提交回复
热议问题