Advertisement
Guest User

Untitled

a guest
Jul 27th, 2016
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 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. public static void main(String[] args) {
  11. // 注意
  12. // 1. Service 視窗必須啟動資料庫服務 Database->JavaDB->Start Server
  13. // 2. 專案程式庫必須加入資料庫驅動程式
  14. String url = "jdbc:derby://localhost:1527/EmployeeDB";
  15. String user = "test";
  16. String pass = "tiger";
  17.  
  18. Connection con = null;
  19. Statement stmt = null;
  20. ResultSet rs = null;
  21.  
  22. try {
  23. // 建立 連線 物件
  24. con = DriverManager.getConnection(url, user, pass); // 連線失敗,con 為 null
  25. // 建立 SQL 陳述句 物件
  26. stmt = con.createStatement();
  27. // 撰寫 SQL 查詢 字串
  28. String query = "select * from employee"; // 查詢所有員工
  29. // 執行 SQL 查詢 , 獲取結果集(ResultSet)
  30. rs = stmt.executeQuery(query);
  31.  
  32. // 取得下一筆資料,若有獲取到資料回傳 true
  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. // 輸出目前所讀到的員工資料
  42. System.out.println(id + " " + firstName + " " + lastName
  43. + " " + birthdate + " " + salary);
  44. }
  45.  
  46. } catch (SQLException ex) { // 捕捉資料庫例外
  47. System.err.println(ex); // err 物件輸出的訊息是紅色的
  48. }
  49. }
  50.  
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement