Sunday, January 30, 2011

Select data from Oracle Database using Java

Okay in this chapter we will make connection between java and oracle database. First we will make user in Oracle.Copy code bellow in your oracle:

Query to create user in oracle database (Note log in with system)
create user dbContact identified by contact12345
grant connect,resource to dbContact

Query to make table in oracle (Note:Log in with dbContact)
create table Contact(
ID varchar2(100) primary key not null, Name varchar2(100), Address varchar2(100)
)

Query insert data to table Contact
insert into Contact values('1','Yohan Andreas','Babakan Jeruk I')
insert into Contact values('2','Hendry Apryanto','Kampung Hutan Tua')
insert into Contact values('3','Tana El San','Surya Sumantri')

Class in Java
ConnectionDatabase.java


import java.sql.*;
public class ConnectionDatabase {
Connection conn=null;

public Connection getConnection() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@127.0.0.1:1521:ORCL";
String _user="dbContact";
String _pass="contact12345";
conn=DriverManager.getConnection(url,_user,_pass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch ( SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void main (String[] args) {
new ConnectionDatabase().getConnection();
}
}


SelectDatabase.java

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SelectDatabase {

public ConnectionDatabase conn = new ConnectionDatabase();
public Connection conx = null;
public ResultSet set=null;

public SelectDatabase() {
String sql = "Select * from Contact";
conx = conn.getConnection();
try {
Statement stat = conx.createStatement();
set = stat.executeQuery(sql);
while (set.next()) {
System.out.println("ID Contact :" + set.getString("ID"));
System.out.println("Name Contact :" + set.getString("NAME"));
System.out.println("Address :" + set.getString("ADDRESS"));
System.out.print("\n");
}
} catch (SQLException ex) {
Logger.getLogger(SelectDatabase.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
new SelectDatabase();
}
}


Result:



Okay that's is it and congratulation you have made connection between java and oracle and you can display data. I hope this tutorial can help you..Thank you...^^

No comments:

Post a Comment