Bài giảng Lập trình hướng đối tượng - Bài 9: Java kết nối cơ sở dữ liệu - TS. Nguyễn Mạnh Hùng

pdf 23 trang phuongnguyen 3690
Bạn đang xem 20 trang mẫu của tài liệu "Bài giảng Lập trình hướng đối tượng - Bài 9: Java kết nối cơ sở dữ liệu - TS. Nguyễn Mạnh Hùng", để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên

Tài liệu đính kèm:

  • pdfbai_giang_lap_trinh_huong_doi_tuong_bai_9_java_ket_noi_co_so.pdf

Nội dung text: Bài giảng Lập trình hướng đối tượng - Bài 9: Java kết nối cơ sở dữ liệu - TS. Nguyễn Mạnh Hùng

  1. Lập trình hướng đối tượng Java kết nối cơ sở dữ liệu Giảng viên: TS. Nguyễn Mạnh Hùng Học viện Công nghệ Bưu chính Viễn thông (PTIT)
  2. Nội dung  Kết nối với DB bằng JDBC  Chuẩn bị câu lệnh QSL  Lấy kết quả ra xử lí  Làm việc với transaction  Bài tập 2
  3. Kết nối DB bằng JDBC
  4. Kết nối bằng JDBC (1) public Connection getConnection(String dbClass, String dbUrl) throws SQLException { Connection conn = null; try { Class.forName(dbClass); Connection conn = DriverManager.getConnection (dbUrl); }catch(ClassNotFoundException e) { e.printStackTrace(); }catch(SQLException e) { throws e; } return conn; } String dbClass = "com.mysql.jdbc.Driver"; String dbUrl = "jdbc:mysql://your.database.domain/yourDBname"; 4
  5. Kết nối bằng JDBC (2) public Connection getConnection(String dbClass, String dbUrl, String userName, String password) throws SQLException { Connection conn = null; try { Class.forName(dbClass); Connection conn = DriverManager.getConnection (dbUrl, userName, password); }catch(ClassNotFoundException e) { e.printStackTrace(); }catch(SQLException e) { throws e; } return conn; } String dbClass = "com.mysql.jdbc.Driver"; String dbUrl = "jdbc:mysql://your.database.domain/yourDBname"; 5
  6. Chuẩn bị câu lệnh SQL
  7. Dùng Statement (1) String query = "Select * FROM users"; String query = "INSERT INTO users VALUES(« aaa », « bbb »)"; String query = "UPDATE password FROM users WHERE id = 111 VALUE(« ccc »)"; String query = "DELETE FROM users HERE id = 111"; 7
  8. Dùng Statement (2) try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); }catch(ClassNotFoundException e) { e.printStackTrace(); }catch(SQLException e) { e.printStackTrace(); } 8
  9. Dùng PreparedStatement PreparedStatement updateSales = null; String updateString = "update products " + "set SALES = ? where ID = ?"; try { updateSales = conn.prepareStatement(updateString); updateSales.setInt(1, value); updateSales.setInt(2, productId); updateSales.executeUpdate(); } catch (SQLException e ) { throw e; } 9
  10. Bài tập Có hai bảng CSDL: Transaction: productId (int), value (int), dateOfTransaction(Date) Sumary: productId (int), totalValue (int) • Viết các preparedStatement cho việc tìm các giao dịch có giá trị >= X • Viết các preparedStatement cho việc tìm các sản phẩm có giá trị giao dịch trung bình >= X 10
  11. Dùng StoreProcedure (1) String createProcedure = "create procedure GET_MAX_OF_SALE(IN productId int, OUT value int) " + "begin " + "select MAX(value) into productValue " + "from products " + "where ID = productId; " + "select productValue; " + "end"; try { Statement stmt = conn.createStatement(); stmt.executeUpdate(createProcedure); } catch (SQLException e ) { throw e; } 11
  12. Dùng StoreProcedure (2) try { CallableStatement cs = conn.prepareCall("{call SHOW_MAX_OF_SALE(?,?)}"); ResultSet rs = cs.executeQuery(); cs.setInt(1, productId); cs.registerOutParameter(2, Types.INT); cs.executeQuery(); int maxValue = cs.getInt(2); } catch (SQLException e ) { throw e; } 12
  13. Bài tập Có hai bảng CSDL: Transaction: productId (int), value (int), dateOfTransaction(Date) Sumary: productId (int), totalValue (int) • Viết các storeProcedure cho việc tìm các giao dịch có giá trị >= X • Viết các storeProcedure cho việc tìm các sản phẩm có giá trị giao dịch trung bình >= X 13
  14. Lấy dữ liệu ra
  15. Dữ liệu từ ResultSet (1) String query = "Select * FROM users"; try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { System.out.println(rs.getString(1)); } }catch(SQLException e) { e.printStackTrace(); } 15
  16. Dữ liệu từ ResultSet (2) String query = "Select * FROM users"; try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); // get number of row in resultSet int rowcount = 0; if (rs.last()) { rowcount = rs.getRow(); rs.beforeFirst(); // not rs.first() } while (rs.next()) { // do something with data } }catch(SQLException e) { e.printStackTrace(); } 16
  17. Bài tập Có hai bảng CSDL: Transaction: productId (int), value (int), dateOfTransaction(Date) Sumary: productId (int), totalValue (int) • Viết chương trình đầy đủ cho việc tìm các giao dịch có giá trị >= X • Viết chương trình đầy đủ cho việc tìm các sản phẩm có giá trị giao dịch trung bình >= X 17
  18. Làm việc với Transaction
  19. Điều khiển chế độ commit (1) try { conn.setAutoCommit(false); conn.commit(); } catch (SQLException e ) { if (conn != null) { try { conn.rollback(); } catch(SQLException excep) { throw excep; } } throw e; } finally { conn.setAutoCommit(true); } } 19
  20. Điều khiển chế độ commit (2) public void updateSales(int productId, int value) throws SQLException { PreparedStatement updateSales = null; PreparedStatement updateTotal = null; String updateString = "update products " + "set SALES = ? where ID = ?"; String updateStatement = "update totalSale " + "set TOTAL = TOTAL + ? where productId = ?"; try { conn.setAutoCommit(false); updateSales = conn.prepareStatement(updateString); updateTotal = conn.prepareStatement(updateStatement); updateSales.setInt(1, value); updateSales.setInt(2, productId); updateSales.executeUpdate(); 20
  21. Điều khiển chế độ commit (3) updateTotal.setInt(1, value); updateTotal.setInt(2, productId); updateTotal.executeUpdate(); conn.commit(); } catch (SQLException e ) { if (conn != null) { try { conn.rollback(); } catch(SQLException excep) { throw excep; } } throw e; } finally { if (updateSales != null) { updateSales.close(); } if (updateTotal != null) { updateTotal.close(); } conn.setAutoCommit(true); } } 21
  22. Bài tập  Cài đặt một ứng dụng CSDL  Viết hàm main cho phần phần đã cài đặt 22
  23. Questions?