4

We want our own db connection configuration instead of using JNDI, but in the meantime, we also want to use DataSource instead of using DriverManager, how to do so?

imgen
  • 2,613
  • 6
  • 40
  • 59

2 Answers2

7

You use a connection pool library like c3p0 or commons dbcp.

C3P0

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

Connection connection = cpds.getConnection();

DBCP

BasicDataSource ds= new BasicDataSource();
ds.setDriverClassName("org.postgresql.Driver");
ds.setUrl("jdbc:postgresql://localhost/testdb");
ds.setUsername("dbuser");
ds.setPassword("dbpassword");

Connection connection = ds.getConnection();
Greg Brown
  • 2,993
  • 1
  • 26
  • 36
Arun P Johny
  • 376,738
  • 64
  • 519
  • 520
3

You can use org.apache.commons.dbcp.BasicDataSource

BasicDataSource ds= new BasicDataSource();
ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
ds.setUrl("jdbc:oracle:thin:@dburl:port:sid");
ds.setUsername("uname");
ds.setPassword("pass");
Anubhab
  • 1,696
  • 2
  • 18
  • 28