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();