There are a couple of ways to connect to a recent Oracle Database, going through the standard DriverManager class or the specific OracleDataSource one. Let's see both of them. And, when we are there, let's add also some consideration on connecting to MySql via DriverManager.
It's a bit of an overkill, but I have written a little abstract class that is going to be the root of a hierarchy of classes for providing access to database through JDBC:
public abstract class Connector {
public abstract Connection getConnection() throws SQLException;
public String getDatabaseVersion(Connection conn) throws SQLException {
return conn.getMetaData().getDatabaseProductVersion();
}
}
The point of it is that each different concrete class has its own way to get a database connection but all of them would use it in the same way. So the getConnection() method is abstract where the actual method performing JDBC operation, like getDatabaseVersion(), would act in the same way.
Using OracleDataSource
The OracleDataSourceConnector extends Connector, and its raison d'être is keeping an instance of a OracleDataSource object as its private data member. Initialized in the constructor, is used by the the getConnection() method to return a database connection.
public class OracleDataSourceConnector extends Connector {
private OracleDataSource ods;
public OracleDataSourceConnector(String url, String user, String password) throws SQLException {
ods = new OracleDataSource();
ods.setURL(url);
ods.setUser(user);
ods.setPassword(password);
}
@Override
public Connection getConnection() throws SQLException {
return ods.getConnection();
}
}
The good thing about OracleDataSource is that it has its own pool of connections that is managed implicitly. On the flip side, it is not standard JDBC. That means extra work if we want to adapt our code to use a different database.
I have written a tester to check the functionality, OracleDataSourceConnectorTest. See it on GitHub for full reference. There are only a few things that I want to stress here.
public class OracleDataSourceConnectorTest {
private static final String URL = "jdbc:oracle:thin:@localhost:1521/orclpdb"; // 1
private static final String USER = "hr";
private static final String PASSWORD = "hr";
private static OracleDataSourceConnector ods;
private static Connection conn;
@BeforeClass
public static void setUp() { // 2
try {
ods = new OracleDataSourceConnector(URL, USER, PASSWORD);
conn = ods.getConnection();
} catch (SQLException e) {
fail(e.getMessage());
}
}
// ...
}
1. I'm using the thin Oracle JDBC driver, the other choice is the OCI one. See the Oracle documentation if you wonder which one to use. Short answer is, usually thin is the one you want to peek. My database is local, on the standard port, and the service is named orclpdb. Your setup may vary.
2. I setup the connector and a connection through this static method called only once before the tests in the class are called. The sense is that I don't want to repeat expensive operations without a reason. So, when nothing is against it, I would reuse connector and connection in more tests.
And here is a test that requires its own connector, because I want to perform a disruptive negative test:
@Test
public void testBadUser() {
OracleDataSourceConnector connector = null;
try {
connector = new OracleDataSourceConnector(URL, "Unknown", PASSWORD); // 1
} catch (SQLException e) {
fail(e.getMessage());
}
try {
connector.getConnection(); // 2
fail("No connection expected for unknown user");
} catch (SQLException e) {
String expectedState = "72000";
assertEquals(expectedState, e.getSQLState());
int expectedCode = 1017;
assertEquals(expectedCode, e.getErrorCode());
}
}
1. I pass a bas user name to the connector. No failure is expected here, since no connection is actually done.
2. I expect the failure to happen here. Oracle should react with a ORA-01017 error code, that is included in the SQL state 72000, SQL execute phase errors.
The other test ensures that I can actually get to the database:
@Test
public void testGetDatabaseNameVersion() {
try {
String expected = "Oracle Database 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Production";
String actual = ods.getDatabaseVersion(conn);
assertEquals(expected, actual);
} catch (SQLException e) {
fail(e.getMessage());
}
}
Using DriverManager
If I am not interested in the connection pooling service offered by OracleDataSource, and I prefer to keep as generic as I can, I could use these other solution. In the old days, it required to perform an explicit registration of the JDBC driver:
Class.forName(klass)
Where klass is the actual class name, like "oracle.jdbc.driver.OracleDriver" or "com.mysql.jdbc.Driver".
Now this is done implicitly by the DriverManager, that leads to a very slim connector:
public class PlainConnector extends Connector {
private String url;
private String user;
private String password;
public PlainConnector(String url, String user, String password) {
this.url = url;
this.user = user;
this.password = password;
}
@Override
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
}
The constructor just store a copy of the data for connecting to the database, the getConnection() uses them going through DriverManager.
I have written another test case to see that actually the plain connector works as the OracleDataSource one. An then another one to see what I have to change to access with the same class a different database, here MySql.
This test case is accessing a MySql database that I have installed locally and on which I have added a user named "hr", to keep it close to the Oracle one. You can see how minimal are the required changes.
I had to change the URL:
private static final String URL = "jdbc:mysql://localhost:3306/hr?useSSL=false";
Notice the parameter useSLL set to false, to remove the MySql warning "Establishing SSL connection without server's identity verification is not recommended." In this test we can live without id verification.
In case of bad user, I expect now 28000 as SQL state and 1045, access denied, as error code.
And, the database version now should be something like "5.7.19-log"
Ah, right. Remember to put in your application build path the jar for oracle JDBC (currently named ojdbc8.jar) and for MySql (mysql-connector-java-5.1.43-bin.jar) and to have the databases up and running, if you want your tests to succeed.
Reference: Oracle Database JDBC Developer's Guide 12c Release 2
Full Java code on GitHub.
Go to the full post