Advertisement
Guest User

Untitled

a guest
Jan 17th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.Collection;
  7. import java.util.HashSet;
  8.  
  9. public class EmployeeDAO_JDBCImpl implements EmployeeDAO {
  10.  
  11. private Connection con = null;
  12.  
  13. public EmployeeDAO_JDBCImpl() {
  14.  
  15. String url = "jdbc:derby://localhost:1527/EmployeeDB";
  16. String user = "test";
  17. String pass = "tiger";
  18.  
  19. try {
  20. // 建立 連線 物件
  21. con = DriverManager.getConnection(url, user, pass); // 連線失敗,con 為 null
  22.  
  23. } catch (SQLException ex) { // 捕捉資料庫例外
  24. System.out.println(ex);
  25. }
  26.  
  27. }
  28.  
  29. @Override
  30. public void add(Employee emp) {
  31.  
  32. }
  33.  
  34. @Override
  35. public void update(Employee emp) {
  36. }
  37.  
  38. @Override
  39. public void delete(int id) {
  40. }
  41.  
  42. @Override
  43. public Employee findById(int id) {
  44. return null;
  45. }
  46.  
  47. @Override
  48. public Employee[] getAllEmployees() {
  49.  
  50. Collection<Employee> collection = new HashSet<>();
  51.  
  52. String query = "select * from employee"; // 查詢所有員工
  53.  
  54. // auto close
  55. try(Statement stmt = con.createStatement();
  56. ResultSet rs = stmt.executeQuery(query);) {
  57.  
  58. while (rs.next()) { // 取得下一筆資料,若有獲取到資料回傳 true
  59. // 讀取目前這筆資料的各項欄位
  60. int id = rs.getInt("id");
  61. String firstName = rs.getString("firstname");
  62. String lastName = rs.getString("lastname");
  63. java.util.Date birthdate = rs.getDate("birthdate");
  64. float salary = rs.getFloat("salary");
  65.  
  66. Employee emp = new Employee(id, firstName, lastName, birthdate, salary);
  67. collection.add(emp);
  68.  
  69. } // while
  70.  
  71. return collection.toArray(new Employee[0]);
  72.  
  73. } catch (SQLException ex) { // 捕捉資料庫例外
  74. System.out.println(ex);
  75. }
  76. return null;
  77. }
  78.  
  79. @Override
  80. public void close() throws Exception {
  81.  
  82. try { if (con != null) con.close(); } catch (SQLException ex) { System.out.println(ex); }
  83. }
  84.  
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement