Oracle JDBC example in Java.
Class.forName("oracle.jdbc.driver.OracleDriver"); Connection connection = null; connection = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:ziben","username","password"); connection.close();
See a full example to show you how to connect to Oracle database via Oracle JDBC driver in Java.
File : OracleJDBC.java
import java.sql.DriverManager; import java.sql.Connection; import java.sql.SQLException; public class OracleJDBC { public static void main(String[] argv) { System.out.println("-------- Oracle JDBC Connection Testing ------------"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { System.out.println("Where is your Oracle JDBC Driver?"); e.printStackTrace(); return; } System.out.println("Oracle JDBC Driver Registered!"); Connection connection = null; try { connection = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:ziben","username","password"); } catch (SQLException e) { System.out.println("Connection Failed! Check output console"); e.printStackTrace(); return; } if (connection != null){ System.out.println("You made it, take control your database now!"); }else{ System.out.println("Failed to make connection!"); } } }
How to run it?
Assume OracleJDBC.java
is store in “/home/ziben/jdbc-test
” folder, together with Oracle JDBC driver (ojdbc6.jar), then run following commands :
/home/ziben/jdbc-test
$ javac OracleJDBC.java/home/ziben/jdbc-test$
java -cp/home/ziben/jdbc-test/
jdbc-test/ojdbc6.jar;/home/ziben/jdbc-test/
jdbc-test OracleJDBC -------- Oracle JDBC Connection Testing ------------ Oracle JDBC Driver Registered! You made it, take control your database now!/home/ziben/jdbc-test$