Test JDBC connectivity to Oracle using Java

This blogs shows how to connect to Oracle database to test a JDBC connection:

https://www.quickprogrammingtips.com/java/connecting-to-oracle-database-in-java.html

Put the below java code in a text file in linux called: OracleSample.java

——————————————————————————————————————–

// Example Java Program – Oracle Database Connectivity
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class OracleSample {

public static final String DBURL = “jdbc:oracle:thin:@oraclehostname:1521/servicename”;
public static final String DBUSER = “userid”;
public static final String DBPASS = “password”;

public static void main(String[] args) throws SQLException {

// Load Oracle JDBC Driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

// Connect to Oracle Database
Connection con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);

Statement statement = con.createStatement();

// Execute a SELECT query on Oracle Dummy DUAL Table. Useful for retrieving system values
// Enables us to retrieve values as if querying from a table
ResultSet rs = statement.executeQuery(“SELECT SYSDATE FROM DUAL”);

if (rs.next()) {
Date currentDate = rs.getDate(1); // get first column returned
System.out.println(“Current Date from Oracle is : “+currentDate);
}
rs.close();
statement.close();
con.close();
}
}

———————————————————————————————————————-

Compile the java code:

javac -classpath /path-to-jdbc-driver/ojdbc8.jar OracleSample.java

Run the code as:

java -classpath “/path-to-jdbc-driver/ojdbc8jav.jar:.” OracleSample

This will give the result:

Current Date from Oracle is : 2018-04-12

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.