i am working on a MVC project in java. For my operation I use database many times. many times my database connection gives my error like connection is not free to use. So I want to create a connection pool with my mysql database which is present on a remote server. Please help. Thanks in advance.
I would use apache commons dbcp: https://commons.apache.org/proper/commons-dbcp/
Assuming you have a Properties
object with all the JDBC parameters, you can create a connection pool with:
private static DataSource createDataSource(Properties props)
throws Exception {
return BasicDataSourceFactory.createDataSource(props);
}
If you want to emulate the behavious of an appserver, you can put this datasource in a JNDI container; otherwise, you can just assign it to a static variable.
Now, when whenever you need a JDBC connection, you do:
try (Connection cnt = myDataSource.getConnection();
PreparedStatement stmt = cnt.prepareStatement("...")) {
// lots of very useful things
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.