Lập trình Java với Oracle Database

Bài này chủ yếu tôi đưa ra các ví dụ hướng dẫn các bạn lập trình ngôn ngữ Java thao tác với Oracle database bao gồm query dữ liệu, thực hiện các câu lệnh DML, gọi hàm và thủ tục trong database và cách tạo hàm và thủ tục trong Oracle database từ một Java class. 1. Kết nối và thao tác với Oracle database: example /** class này khai báo kết nối với Oracle database áp dụng khái niệm singleton. Khi sử dụng Oracle driver các bạn phải chép file classes12.jar vào thư mục WEB-INF/lib. File này các bạn có thể tìm thấy trong thư mục oracle_home/jdbc/lib */ package javaora.example; import java.sql.*; public class ConnectionProvider { private static Connection connection = null; // thông số database có thể là tên ODBC nếu các bạn sử dụng ODBC driver // hoặc ở dạng hostnameort:sid nếu dùng Oracle driver public Connection openConnection(String driver, String database, String username, String password) { if (connection == null) { try{ if (driver.equals("Oracle")){ Class.forName("oracle.jdbc.driver.OracleDriver"); connection = DriverManager.getConnection("jdbcracle:thin:@"+database,username,password); } else { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); connection = DriverManager.getConnection("jdbcdbc:"+database,username,password); } } catch (ClassNotFoundException cnfe){ System.err.println("Driver not found."); } catch (SQLException e) { System.err.println(e.getMessage()); } } return connection; } public void closeConnection(){ try {connection.close();} catch(SQLException eSQL){} finally {connection = null;} } }

doc8 trang | Chia sẻ: tlsuongmuoi | Lượt xem: 3629 | Lượt tải: 2download
Bạn đang xem nội dung tài liệu Lập trình Java với Oracle Database, để tải tài liệu về máy bạn click vào nút DOWNLOAD ở trên
KẾT NỐI VÀO ORACLE - Bài 7: Lập trình Java với Oracle Database Tác giả: www.oravn.com  Bài này chủ yếu tôi đưa ra các ví dụ hướng dẫn các bạn lập trình ngôn ngữ Java thao tác với Oracle database bao gồm query dữ liệu, thực hiện các câu lệnh DML, gọi hàm và thủ tục trong database và cách tạo hàm và thủ tục trong Oracle database từ một Java class. 1. Kết nối và thao tác với Oracle database: example /** class này khai báo kết nối với Oracle database áp dụng khái niệm singleton. Khi sử dụng Oracle driver các bạn phải chép file classes12.jar vào thư mục WEB-INF/lib. File này các bạn có thể tìm thấy trong thư mục oracle_home/jdbc/lib */ package javaora.example; import java.sql.*; public class ConnectionProvider {   private static Connection connection = null;   // thông số database có thể là tên ODBC nếu các bạn sử dụng ODBC driver   // hoặc ở dạng hostname:port:sid nếu dùng Oracle driver   public Connection openConnection(String driver, String database, String username, String password) {     if (connection == null) {       try{         if (driver.equals("Oracle")){           Class.forName("oracle.jdbc.driver.OracleDriver");           connection = DriverManager.getConnection("jdbc:oracle:thin:@"+database,username,password);         }         else {           Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");           connection = DriverManager.getConnection("jdbc:odbc:"+database,username,password);         }       }       catch (ClassNotFoundException cnfe){         System.err.println("Driver not found.");       }       catch (SQLException e) {         System.err.println(e.getMessage());       }     }     return connection;   }   public void closeConnection(){     try {connection.close();}     catch(SQLException eSQL){}     finally {connection = null;}   } } /** employee bean */ package javaora.example; public class Employee {     private int employeeID;     private String firstname;     private String lastname;     private String email;     private String phone;     private String hiredate;     private String jobID;     private double salary;     private double commission;     private int managerID;     private int departmentID;     public int getEmployeeID() {         return employeeID;     }     public void setEmployeeID(int value) {         employeeID = value;     }     public String getFirstname() {         return firstname;     }     public void setFirstname(String value) {         firstname = value;     }     public String getLastname() {         return lastname;     }     public void setLastname(String value) {         lastname = value;     }     public String getEmail() {         return email;     }     public void setEmail(String value) {         email = value;     }     public String getPhone() {         return phone;     }     public void setPhone(String value) {         phone = value;     }     public String getHiredate() {         return hiredate;     }     public void setHiredate(String value) {         hiredate = value;     }     public String getJobID() {         return jobID;     }     public void setJobID(String value) {         jobID = value;     }     public double getSalary() {         return salary;     }     public void setSalary(double value) {         salary = value;     }     public double getCommission() {         return commission;     }     public void setCommission(double value) {         commission = value;     }     public int getManagerID() {         return managerID;     }     public void setManagerID(int value) {         managerID = value;     }     public int getDepartmentID() {         return departmentID;     }     public void setDepartmentID(int value) {         departmentID = value;     }     public String toString(){         return "Employee Id: "+ employeeID +                " Name: "+ firstname +", "+ lastname +                " Job Id: "+ jobID +                " E-Mail: "+ email +                " Phone: "+ phone +                " Department: "+ departmentID;     } } /** employee database access object (DAO) các bạn xem cách khai báo và sử dụng Statement, PreparedStatement để thực thi select statments và DML, CallableStatement để gọi stored procedure, ResultSet để query dữ liệu. Lưu ý là tôi đưa phần bắt exception ra servlet, khi thực thi nó sẽ forward success.jsp hoặc failure.jsp */ package javaora.example; import java.sql.*; public class EmployeeService{   private Connection connection = null;   public EmployeeService(){     this("Oracle","dataserver:1521:edu","hr","hr");   }   public EmployeeService(String driver, String database, String username, String password){     connection = ConnectionProvider.openConnection(driver, database, username, password);   }   private String formatDate(String date){     if ((date == null) || (date.length() == 0)) {       return "null";     }     else {         return "to_date('" + date + "','mm/dd/yyyy')";     }   }   public void addEmployee (Employee user) throws SQLException {     String date = formatDate(user.getHiredate());       Statement stmt = connection.createStatement();       String sql = "insert into employees (employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, commission_pct, manager_id, department_id) values("                   + user.getEmployeeID() + ", '" + user.getFirstname() + "', '" + user.getLastname() + "', '" + user.getEmail() + "', '" + user.getPhone() + "', "+ date +", '" + user.getJobID()                   + "', " + user.getSalary() + ", " + user.getCommission() + ", " + user.getManagerID() + ", " + user.getDepartmentID() + ")";       stmt.executeUpdate(sql);       stmt.close();   }   public void addEmployee (int id, String fname, String lname, String email, String phone, String hiredate, String job, double salary, double commission, int managerID, int departmentID) throws SQLException {     String date = formatDate(hiredate);       Statement stmt = connection.createStatement();       String sql = "insert into employees (employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, commission_pct, manager_id, department_id) values("                   + id + ", '" + fname + "', '" + lname + "', '" + email + "', '" + phone + "', "+ date +", '" + job                   + "', " + salary + ", " + commission + ", " + managerID + ", " + departmentID + ")";       stmt.executeUpdate(sql);       stmt.close();   }   public void deleteEmployee (int userID) throws SQLException {       PreparedStatement pstmt = connection.prepareStatement("delete from employees where employee_id = ?");       pstmt.setInt(1,userID);       pstmt.execute();   }   public void updateEmployee (int id, String field, String value) throws SQLException {     String newValue = "";     if (field.equalsIgnoreCase("hire_date")){       newValue = formatDate(value);     }     else {newValue = "'"+ value +"'";}       Statement stmt = connection.createStatement();       String upd = "update employees set "+ field +"="+ newValue + " where employee_id="+ id;       stmt.executeUpdate(upd);       stmt.close();   }   public void updateEmployee (Employee user) throws SQLException {     String date = formatDate(user.getHiredate());       Statement stmt = connection.createStatement();       String upd = "update employees set first_name = '" + user.getFirstname() + "', last_name = '"+ user.getLastname() +"', email = '" + user.getEmail() + "', phone = '" + user.getPhone() + "', hire_date = "+ date +", job_id = '" + user.getJobID() + "', salary = " + user.getSalary() + ", commission_pct = " + user.getCommission() + ", manager_id = " + user.getManagerID() + ", department_id = " + user.getDepartmentID() + " where employee_id = " + user.getEmployeeID();       stmt.executeUpdate(upd);       stmt.close();   }   public Employee getEmployee (int id) throws SQLException {     Employee employee = new Employee();       Statement stmt = connection.createStatement();       ResultSet rs = stmt.executeQuery("select employee_id, first_name, last_name, email, phone_number, to_char(hire_date,'dd/mm/yyyy') hire_date, job_id, salary, commission_pct, manager_id, department_id from employees where employee_id = "+ id);       if (rs.next()){         employee.setEmployeeID(rs.getInt(1));         employee.setFirstname(rs.getString(2));         employee.setLastname(rs.getString(3));         employee.setEmail(rs.getString(4));         employee.setPhone(rs.getString(5));         employee.setHiredate(rs.getString(6));         employee.setJobID(rs.getString(7));         employee.setSalary(rs.getDouble(8));         employee.setCommission(rs.getDouble(9));         employee.setManagerID(rs.getInt(10));         employee.setDepartmentID(rs.getInt(11));       }       rs.close();       stmt.close();       return employee;   } // tôi giả sử trong database có hàm findEmployee sẽ trả về 0 nếu không tìm thấy ngược lại trả ra > 0   public boolean foundEmployee(int id) {     boolean result = false;     try {       CallableStatement cstmt = connection.prepareCall("{?= call findEmployee("+id+")}");       cstmt.registerOutParameter(1,Types.INTEGER);       cstmt.execute();       int out = cstmt.getInt(1);       if (out > 0) result = true;       cstmt.close();     }     catch (SQLException eSQL){       System.err.println(eSQL.getMessage());     }     finally {return result;}   } } 2. Tạo hàm, thủ tục từ một Java class Nếu các bạn đã viết các phương thức bằng Java và nó đã chạy tốt thì các bạn có thể khai báo thành hàm hay thủ tục trong Oracle database mà không cần chuyển sang ngôn ngữ PL/SQL create or replace and compile java source named "JavaDemo" as public class JavaDemo{   public static void greeting(String[] hello){     hello[0] = "value return from a Java method";   }   public static String sayHello(){     return "hello from a Java class";   } } / create or replace procedure OraGreeting(p_hello out varchar2) as language java name 'JavaDemo.greeting(java.lang.String[])' ; / create or replace function OraHello return varchar2 as language java name 'JavaDemo.sayHello() return java.lang.String' ; / // thực thi ở sqlplus variable hello varchar2(50); exec oragreeting(:hello) print hello exec :hello := OraHello print hello

Các file đính kèm theo tài liệu này:

  • docLập trình Java với Oracle Database.doc
Tài liệu liên quan