Monday, August 3, 2009

Source code to connect to a Oracle Database – Java

This is sample source code to connect to Oracle Database.
You need to have Oracle Driver [Can be downloaded from http://www.findjar.com/jar/mule/dependencies/maven1/oracle-jdbc/jars/ojdbc14.jar.html], the ip address of the machine where database exists and service identifier of the database. We use 1521 as a default ip address to connect to the database.



/*
* DBConnection.java
*/

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class DBConnection {

Connection con;
DBConnection() {
}

private void dbInitiateConnection() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch(NullPointerException npe) {
npe.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}

try {
con = DriverManager.getConnection("jdbc:oracle:thin:@ipaddress:1521:serviceidentifierofdatabase","username","password");
con.setAutoCommit(false);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}


private void getDataFromTable() {
try {
PreparedStatement psd = con.prepareStatement("select empno from emp");
ResultSet rst = psd.executeQuery();
System.out.println("Employee Nos are ");
while(rst.next()){
int empNo = rst.getInt(1);
System.out.println(empNo);
}
rst.close();
psd.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}




private void dbCloseConnection() {
try {
con.close();
} catch(SQLException ex) {
ex.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}

public static void main(String args[]) {
DBConnection dbConnect = new DBConnection();
dbConnect.dbInitiateConnection();
dbConnect.getDataFromTable();
dbConnect.dbCloseConnection();
}

}

No comments:

Total Pageviews