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 needed?
Absolutely it is safe to do this. This is how client-server applications work. If you are using a three-tier application, the application server will keep a pool of connections open anyway.
Usually you'd only want to open a connection to your database when you need to use that connection. Keeping connections open can increase the chance that part of your code will accidentally, or maliciously through the actions of others, cause unwanted queries to be performed on the database.
For the purpose of safe coding, you should always close database connections explicitly to make sure that the code was able to close itself gracefully and to prevent any other objects from reusing the same connection after you are done with it.
If you don't close it, it leaks, and ties up server resources. @EJP The connection itself might be thread-safe (required by JDBC), but the applications use of the connection is probably not threadsafe. Think of things like different transaction isolation, boundaries (commit/rollback/autocommit) etc.
The database connection must be opened only when its needed and closed after doing all the necessary job with it. Code sample:
Prior to Java 7:
Connection con = null; try { con = ... //retrieve the database connection //do your work... } catch (SQLException e) { //handle the exception } finally { try { if (con != null) { con.close(); } } catch (SQLException shouldNotHandleMe) { //... } }
Java 7:
try (Connection con = ...) { } catch (SQLException e) { } //no need to call Connection#close since now Connection interface extends Autocloseable
But since manually opening a database connection is too expensive, it is highly recommended to use a database connection pool, represented in Java with DataSource
interface. This will handle the physical database connections for you and when you close it (i.e. calling Connection#close
), the physical database connection will just be in SLEEP mode and still be open.
Related Q/A:
Some tools to handle database connection pooling:
Depends on what are your needs.
Creating a connection takes some time, so if you need to access database frequently it's better to keep the connection open. Also it's better to create a pool, so that many users can access database simultaneously(if it's needed).
If you need to use this connection only few times you may not keep it open, but you will have delay when you would like to access database. So i suggest you to make a timer that will keep connection open for some time(connection timeout).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With