Advertisement
Guest User

Untitled

a guest
Jan 12th, 2017
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. public class Test1 {
  2. public static void main(String[] args) {
  3. // 注意
  4. // 1. Service 視窗必須啟動資料庫服務 Database->JavaDB->Start Server
  5. // 2. 專案程式庫必須加入資料庫驅動程式
  6. String url = "jdbc:derby://localhost:1527/EmployeeDB";
  7. String user = "test";
  8. String pass = "tiger";
  9.  
  10. Connection con = null;
  11. Statement stmt = null;
  12. ResultSet rs = null;
  13. try {
  14. // 建立 連線 物件
  15. con = DriverManager.getConnection(url, user, pass); // 連線失敗,con 為 null
  16. // 建立 SQL 陳述句 物件
  17. stmt = con.createStatement();
  18. // 撰寫 SQL 查詢 字串
  19. String query = "select * from employee"; // 查詢所有員工
  20. // 執行 SQL 查詢 , 獲取結果集(ResultSet)
  21. rs = stmt.executeQuery(query);
  22. // 逐筆讀取所查詢結果
  23. while (rs.next()) { // 取得下一筆資料,若有獲取到資料回傳 true
  24. // 讀取目前這筆資料的各項欄位
  25. int id = rs.getInt("id");
  26. String firstName = rs.getString("firstname");
  27. String lastName = rs.getString("lastname");
  28. java.util.Date birthdate = rs.getDate("birthdate");
  29. float salary = rs.getFloat("salary");
  30. // 輸出目前所讀到的員工資料
  31. System.out.println(id + " " + firstName + " " + lastName +
  32. " " + birthdate + " " + salary);
  33. } // while
  34. } catch(SQLException e) {
  35. System.err.println(e);
  36. } finally { // try 區塊無論是否發生例外,最後一定會執行
  37. // 關閉資源
  38. // 捕捉關閉資源所發生的例外
  39. try { if (rs != null) rs.close(); } catch (SQLException ex) { System.err.println(ex); }
  40. try { if (stmt != null) stmt.close(); } catch (SQLException ex) { System.err.println(ex); }
  41. try { if (con != null) con.close(); } catch (SQLException ex) { System.err.println(ex); }
  42. } // finally
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement