How to retrieve DB connection using DataSource wit

2019-02-19 10:45发布

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?

标签: java jdbc jndi
2条回答
你好瞎i
2楼-- · 2019-02-19 11:13

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();
查看更多
劳资没心,怎么记你
3楼-- · 2019-02-19 11:16

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");
查看更多
登录 后发表回答