Reputation: 91
I want to connect to Oracle database using DataSource interface not using DriverManager in java. I don't have an idea about this. Please provide me a sample program to do so.
Upvotes: 5
Views: 11301
Reputation: 43053
When you want to use a DataSource here is the way to go:
// Setup the datasource
DataSource ds = new OracleDataSource();// There is other DataSource offered by Oracle , check the javadoc for more information
ds.setDriverType("thin");
ds.setServerName("myServer");
ds.setPortNumber(1521);
ds.setDatabaseName("myDB");
ds.setUser("SCOTT");
ds.setPassword("TIGER");
// Get a JDBC connection
Connection c = ds.getConnection();
This what is roughtly done under the cover.
However, in real life project, you won't often do this. Let's say you build a web application. Usually, you'll configure a datasource in text format and drop this configuration on your container. Later, you can retreive the datasource through JNDI (see @Radhamani Muthusamy answer).
Upvotes: 4
Reputation: 745
// Setting up the DataSource object
oracle.jdbc.pool.OracleDataSource ds
= new oracle.jdbc.pool.OracleDataSource();
ds.setDriverType("thin");
ds.setServerName("localhost");
ds.setPortNumber(1521);
ds.setDatabaseName("XE"); // Oracle SID
ds.setUser("Herong");
ds.setPassword("TopSecret");
// Getting a connection object
con = ds.getConnection();
Upvotes: 0
Reputation: 328
First create a Datasource
file. The datasource filename can be given in properties file
.Use the following code
ResourceBundle rb = ResourceBundle
.getBundle("com.cactus.xorail.properties.ConnectionProperties");
InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup("java:/"
+ rb.getString("Datasource"));
if (ds == null) {
throw new SQLException(
"Please configure datasource with name DS");
}
result = ds.getConnection();
Upvotes: 2