Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve DB connection using DataSource without JNDI?

Tags:

java

jdbc

jndi

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?

like image 651
imgen Avatar asked Oct 26 '25 01:10

imgen


2 Answers

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();
like image 51
Arun P Johny Avatar answered Oct 28 '25 15:10

Arun P Johny


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");
like image 38
Anubhab Avatar answered Oct 28 '25 15:10

Anubhab