Advertisement
Guest User

Untitled

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