Best way to manage DB connections without JNDI

I have a website in which I am currently getting 1,000 pageviews. I expect that in the future he will work about 30 thousand a day. Now the problem is to manage database connections. Currently, I'm just connecting to the database directly from a java program. I know this is the worst design in the world. But this time I wrote it. I have a connection pool management plan using JNDI. But the problem is that my hosting provider does not support JNDI.

Can someone suggest me how to manage DB connections without jndi?

+1
source share
1 answer

The connection pool itself does not require connections that must be obtained by JNDI. You can also simply configure and use the connection pool independently of JNDI. Suppose you would like to use C3P0 , which is one of the best connection pools, then you can find "raw" JNDI - less configuration details in this tutorial .

Here is an excerpt from the textbook:

ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setDriverClass( "org.postgresql.Driver" ); //loads the jdbc driver cpds.setJdbcUrl( "jdbc:postgresql://localhost/testdb" ); cpds.setUser("swaldman"); cpds.setPassword("test-password"); 

Create a data source once during application startup and save it somewhere in context. Then the connection can be obtained and used as follows:

 Connection connection = null; // ... try { connection = cpds.getConnection(); // ... } finally { // ... if (connection != null) try { connection.close(); } catch (SQLException ignore) {} } 

Yes, closing at the end is still required, otherwise the connection pool will not be able to connect the connection in the pool for reuse in the future, and it will end the connection.

+3
source

Source: https://habr.com/ru/post/1493139/


All Articles