CodesJava

Easy learning with example program codes

Connect to Oracle database with JDBC driver

To connect with oracle database with JDBC driver follow the same basic steps discussed in previous tutorials. We have to know the following information to connect with oracle database:

1. Driver class: oracle.jdbc.driver.OracleDriver.

2. Connection URL:
Syntax:

"jdbc:oracle:thin:@localhost:port:serviceName","username", "password"

Connection url for MySql database: jdbc:oracle:thin:@localhost:1521:xe

where 1521 is the port number and XE is the Oracle service name.

3. Username: Username of oracle database, default is system.

4. Password: Password of oracle database.

Example:

JDBCOracleTest.java

import java.sql.Connection;
import java.sql.DriverManager;
 
/**
 * This class is used to create a JDBC 
 * connection with Oracle DB.
 * @author codesjava
 */
public class JDBCOracleTest {
	//JDBC and database properties.
	private static final String DB_DRIVER = 
		           "oracle.jdbc.driver.OracleDriver";
	private static final String DB_URL = 
		        "jdbc:oracle:thin:@localhost:1521:XE";
	private static final String DB_USERNAME = "system";
	private static final String DB_PASSWORD = "oracle";
 
	public static void main(String args[]){
		Connection conn = null;
		try{
			//Register the JDBC driver
			Class.forName(DB_DRIVER);
 
			//Open the connection
			conn = DriverManager.
			getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
 
			if(conn != null){
			   System.out.println("Successfully connected.");
			}else{
			   System.out.println("Failed to connect.");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}	
}

Output:

Successfully connected.

Download this example.
 
Next Topic: Connect to MySql database with JDBC driver.
Previous Topic: Steps to connect with DB.

 

Please follow and like us:
error
Posted in JDBC   








Copyright © 2019 CodesJava DMCA.com Protection Status