4/09/2012

JDBC configuration and implementation (Oracle&Eclipse)

1. Configure JDBC in Eclipse (Database: Oracle 10g Express)
    After we install Oracle 10g Express and Eclipse.
    First download the jar file: "ojdbc14.jar", save it to a safe directory.
    Open Eclipse, New a project.
    Right click on the project: = > Properties = > Java Build Path = >Libraries = >Add External JARs
    Go to the directory of the ojdbc14.jar file and add it to the library.
    Then we can see Reference Libraries under JRE system in workspace.
     Now we finish the JDBC configuration.

2. JDBC code
     First we define JDBC parameters for Oracle 10g Express Edition

     ORACLE_DRIVER = oracle.jdbc.driver.OracleDriver 
     ORACLE_URL = jdbc:oracle:thin:@PCNAME:1521:XE
     ORACLE_USERNAME = XXX
     ORACEL_PASSWORD = XXX

  
     Now we use the parameters to start the code.
     What needs to mention is that in real industry, the database connection methods are always hided into an insulated jar file. So now we better define the connection in a different package from the main code.

01 package com.company.utils;
02 
03 import java.sql.Connection;
04 import java.sql.DriverManager;
05 
06 public class JDBCUtil {
07     private static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
08     private static final String URL = "jdbc:oracle:thin:@PCNAME:1521:XE";
09     private static final String USERNAME = "XXX";
10     private static final String PASSWORD = "XXX";
11     
12     public static  Connection getConnection(){
13         Connection conn = null;
14         try{
15             Class.forName(DRIVER);
16             conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
17             
18         }catch(Exception e){
19             e.printStackTrace();
20         }
21         return conn;
22     }
23 }  
Above is the connection setup. Now we create a table "Sample(Varchar2 Name, Number Age) in Oracle. Execute two queries in the code:

01 package com.company.tests;
02 import java.sql.*;
03 import com.company.utils.*;
04 
05 public class OracleTest1 {
06 
07     
08     public static void main(String[] args){
09         try{
10             
11             Connection conn = JDBCUtil.getConnection();
12             String sql = "insert into Sample Values('Jason',47)";
13             Statement st= conn.createStatement();
14             st.executeUpdate(sql); 
15             sql = "select * from Sample";
16             ResultSet rs = st.executeQuery(sql);
17             while(rs.next()){
18                 System.out.println(rs.getString("Name") + "\t" + rs.getInt("Age"));    
19             }
20             rs.close();
21         }catch(Exception e){
22             e.printStackTrace();
23         }
24     }
25 }


All set! This is the basic part of JDBC.

No comments:

Post a Comment