Tuesday, October 12, 2010

Connect Oracle and Java

It is to connect Oracle database to java program using JDBC (Java Database Connectivity) without use of ODBC (Open Database Connectivity).

import java.sql.*;

public class OracleConn{
public static void main(String[] args) {
System.out.println("Oracle Java Example Program Showing Column/Field Names in a table");
Connection con = null;
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
String driver ="oracle.jdbc.driver.OracleDriver";
String user = "hr";
String pass = "hr";
try
{
Class.forName(driver);
conn = DriverManager.getConnection(url, user, pass);
try{
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("SELECT * FROM employees");
ResultSetMetaData mtdat = rset.getMetaData();
int cols = mtdat.getColumnCount();
System.out.println("Number of Columns : "+ cols);
System.out.println("Columns Name: ");
for (int i = 1; i <= cols; i++){
String col_name = mtdat.getColumnName(i);
System.out.println(col_name);
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

This program connects the database to program and displays the meta data for the table employees. You need to setup the CLASSPATH if you compiling/running the program from command line. Here the database is orcl, the SID. The user name and password here is "hr". Replace the user name and password with if you are connecting to the database as any other user. Save this program in a file named OracleConn.java and Compile it using javac OracleConn.java (from command line) and Run it using command java OracleConn.

No comments:

Post a Comment