简体   繁体   中英

Prepared statements in java

I have a use case where I use memcache to cache certain results from DB. I use the query itself as the key and value will be of type CachedRowSetImpl which serializes the result set. To form the query, I need to use PreparedStatement which in turn needs a connection object to the DB. This defeats the whole purpose of caching since more than half the time is being spent in establishing the connection. Is there any work around for this? Or do I have to use an alternate approach to cache results?

To avoid establishing a connection every time, you use a connection pool, like c3p0 . You configure a connection pool to use Postgres, username swaldman, and passwordComboPooledDataSource

// in constructor
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");                                  

When you need a JDBC Connection, just use:

Connection connection = cpds.getConnection();

There are other connection pools, like DBCP , which are set up in a similar way.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM