Created
July 10, 2012 15:19
-
-
Save lstoll/3083995 to your computer and use it in GitHub Desktop.
JDBC db pooling with DBCP & Heroku
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* based on http://svn.apache.org/viewvc/commons/proper/dbcp/trunk/doc/PoolingDriverExample.java?view=markup | |
* | |
* Run this code when your application starts up to create the pool. | |
*/ | |
// Extract DATABASE_URL environment variable. Set for you on heroku, set it yourself locally | |
URI dbUri = new URI(System.getenv("DATABASE_URL")); | |
String username = dbUri.getUserInfo().split(":")[0]; | |
String password = dbUri.getUserInfo().split(":")[1]; | |
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath(); | |
// Load postgres driver | |
Class.forName( "org.postgresql.Driver" ); | |
// Setup DB pool | |
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(dbUri,username,password); | |
PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory); | |
ObjectPool connectionPool = new GenericObjectPool(poolableConnectionFactory); | |
// Set the maximum number of connections in the pool | |
connectionPool.setMaxActive(5) | |
Class.forName("org.apache.commons.dbcp2.PoolingDriver"); | |
PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:"); | |
driver.registerPool("dbpool",connectionPool); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Example using the pool created above this to get a connection from the pool when you need to access the DB | |
*/ | |
Connection conn = null; | |
Statement stmt = null; | |
ResultSet rset = null; | |
try { | |
conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:dbpool"); | |
stmt = conn.createStatement(); | |
rset = stmt.executeQuery("select * from blah"); | |
// .. do result set stuff here | |
} catch(SQLException e) { | |
e.printStackTrace(); | |
} finally { | |
try { if (rset != null) rset.close(); } catch(Exception e) { } | |
try { if (stmt != null) stmt.close(); } catch(Exception e) { } | |
try { if (conn != null) conn.close(); } catch(Exception e) { } | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment