b02 LTM Java Ket Noi Co So Du Lieu

Preview:

Citation preview

Lập trình mạng Java kết nối cơ sở dữ liệu

Giảng viên: TS. Nguyễn Mạnh HùngHọ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

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";

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";

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";

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();}

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; }

10

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

Dùng StoreProcedure (2)

try { CallableStatement cs =

conn.prepareCall("{call SHOW_MAX_OF_SALE(?,?)}"); cs.setInt(1, productId); cs.registerOutParameter(2, Types.INT); cs.executeQuery(); int maxValue = cs.getInt(2);} catch (SQLException e ) { throw e;}

Lấy dữ liệu ra

13

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();}

14

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 resultSetint 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();}

Làm việc với Transaction

16

Đ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); } }

17

Đ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();

18

Đ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); } }

Ví dụ: Bài toán quản lí đặt phòng khách sạn

20

Bài toán

Một khách sạn (id, tên, địa chỉ, số sao, mô tả) có nhiều phòng (id, hạng phòng, mô tả)

Mỗi phòng có thể được đặt bởi nhiều khách hàng (id, tên, mô tả) tại nhiều thời điểm khác nhau

Mỗi khách hàng có thể đặt nhiều phòng tại nhiều thời điểm khác nhau

Mỗi khách hàng chỉ ở 1 phòng tại 1 thời điểm nhất định, xác định 1 giá xác định

Khách hàng chỉ có thể đặt phòng nếu phòng còn trống trong suốt thời gian khách hàng muốn đặt

Khi trả phòng, nhân viên in phiếu thanh toán bao gồm tên khách sạn, tên khách hàng, số phòng, hạng phòng, ngày đến, ngày đi và tổng số tiền thanh toán

21

Yêu cầu Thiết kế các bảng CSDL cho bài toán Định nghĩa các lớp thực thể cho bài toán Định nghĩa phương thức thêm một phòng khách sạn vào

CSDL Định nghĩa phương thức tìm kiếm danh sách phòng trống

trong một khoảng thời gian xác định Định nghĩa phương thức cho phép 1 khách hàng đặt một

phòng trong một thời gian xác định Định nghĩa phương thức tính doanh thu của khách sạn trong

một thời gian xác định Định nghĩa phương thức liệt kê danh sách các phòng có tỉ lệ

khách hàng đặt cao nhất trong năm

22

Thiết kế CSDL (1) Trước hết cần có 3 bảng:tblHotel: id, name, level, descriptiontblRoom: id, type, descriptiontblCustomer: id, name, username, password, role, descriptionNhận xét: 1 khách sạn có nhiều phòng, 1 phòng chỉ ở trong 1 khách sạn

→ quan hệ giữa bảng tblHotel và tblRoom là 1-n 1 khách hàng đặt nhiều phòng, 1 phòng cũng có nhiều người

đặt → quan hệ giữa tblRoom và tblCustomer là n-n, → phải chuẩn hóa

→ Tạo thêm một bảng đặt chỗ chi tiết tblBooking: idRoom, idCustomer, startDate, endDate, price, description→ quan hệ giữa tblRoom và tblBooking là 1-n (một phòng có nhiều lần đặt), và giữa tblCustomer và tblBooking cũng là 1-n (một người có nhiều lần đặt)

23

Thiết kế CSDL (2)

24

Các lớp thực thể (1) Trước hết cần có 4 lớp:Hotel: id, name, level, description, listRoomRoom: id, type, descriptionCustomer: id, name, username, password, role, descriptionBooking: id, room, customer, startDate, endDate, price, description

Nhận xét: 1 khách sạn có nhiều phòng → thuộc tính listRoom có dạng

một mảng các đối tượng kiểu Room 1 phiếu đặt phòng có 1 phòng → thuộc tính room có dạng một

đối tượng kiểu Room 1 phiếu đặt phòng có 1 khách hàng → thuộc tính customer có

dạng một đối tượng kiểu Customer

25

Các lớp thực thể (2)

26

Thêm phòng (1) String createProcedure = "create procedure ADD_ROOM(IN hotelId int, IN type varchar(50), IN description varchar(50)) " + "begin " + "INSERT INTO tblRoom(hotelId, type, description) " + "VALUES(hotelId, type, description); " + "end"; try { Statement stmt = conn.createStatement(); stmt.executeUpdate(createProcedure); } catch (SQLException e ) { throw e; }

Lưu ý: phần code này viết trong phương thức riêng của lớp control, chỉ cần tạo 1 lần, có thể chạy nhiều lần

27

Thêm phòng (2)

public void addRoom(Room r)throws SQLException{ try { CallableStatement cs =

conn.prepareCall("{call ADD_ROOM(?,?,?)}"); cs.setInt(1, r.getHotelId()); cs.setInt(2, r.getType()); cs.setInt(3, r.getDescription()); cs.executeUpdate(); } catch (SQLException e ) { throw e; } }

Lưu ý: đây là phương thức của lớp control

28

Tìm phòng trống (1) String createProcedure = "create procedure SEARH_FREE_ROOM(IN sDate Date, IN eDate Date " + "begin " + "SELECT * FROM tblRoom WHERE " + "RoomID NOT IN (SELECT RoomId from tblBooking WHERE "+ "((StartDate BETWEEN sDate AND eDate) OR " + "(EndDate BETWEEN sDate AND eDate) OR " + "(sDate BETWEEN StartDate AND EndDate) OR " + "(eDate BETWEEN StartDate AND EndDate)))" + "end"; try { Statement stmt = conn.createStatement(); stmt.executeUpdate(createProcedure); } catch (SQLException e ) { throw e; }

29

Tìm phòng trống (2)public Room[] searchFreeRoom(Date sd, Date ed)throws SQLException{ Room[] result = null; try { CallableStatement cs = conn.prepareCall("{call SEARCH_FREE_ROOM(?,?)}"); cs.setInt(1, sd); cs.setInt(2, ed); ResultSet rs = cs.executeQuery();

if (rs.last()) { result = new Room[rs.getRow()];

rs.beforeFirst(); }

int count = 0; while (rs.next()) { result[count] = new Room(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getString(4)); count++; } } catch (SQLException e ) { throw e;} return result;}

30

Đặt phòng (1) String createProcedure = "create procedure BOOK_ROOM(IN roomId int, IN customerId int, IN sDate Date, IN eDate Date, IN price float, IN description varchar(50))"+ "begin " + "INSERT INTO tblBooking(roomId, customerId, startDate," + "endDate, price, description) VALUES(roomId, customerId, " + "sDate, eDate, price, description); " + "end"; try { Statement stmt = conn.createStatement(); stmt.executeUpdate(createProcedure); } catch (SQLException e ) { throw e; }

Lưu ý: phần code này viết trong phương thức riêng của lớp control, chỉ cần tạo 1 lần, có thể chạy nhiều lần

31

Đặt phòng (2)

public void bookRoom(Booking b)throws SQLException{ try { CallableStatement cs =

conn.prepareCall("{call BOOK_ROOM(?,?,?,?,?,?)}"); cs.setInt(1, b.getRoom().getId()); cs.setInt(2, b.getCustomer().getId()); cs.setInt(3, b.getStartDate()); cs.setInt(4, b.getEndDate()); cs.setInt(5, b.getPrice()); cs.setInt(6, b.getDescription()); cs.executeUpdate(); } catch (SQLException e ) { throw e; } }

Lưu ý: đây là phương thức của lớp control

32

Tính doanh thu (1) String createProcedure = "create procedure TOTAL_INCOME_BY_PERIOD(IN sDate Date, IN eDate Date) " + "begin " + "SELECT SUM(b.price*DATEDIFF(DAY, b.startDate, b.endDate))"+ "FROM tblBooking b WHERE "+ "((b.startDate BETWEEN sDate AND eDate) AND " + "(b.endDate BETWEEN sDate AND eDate)))" + "end"; try { Statement stmt = conn.createStatement(); stmt.executeUpdate(createProcedure); } catch (SQLException e ) { throw e; }

Lưu ý: phần code này viết trong phương thức riêng của lớp control, chỉ cần tạo 1 lần, có thể chạy nhiều lần

33

Tính doanh thu (2)

public double totalIncomeByPeriod(Date sd, Date ed)throws SQLException{ double result = 0; try { CallableStatement cs =

conn.prepareCall("{call TOTAL_INCOME_BY_PERIOD(?,?)}"); cs.setInt(1, sd); cs.setInt(2, ed); ResultSet rs = cs.executeQuery(); if(rs.next()){ result = rs.getDouble(1); } } catch (SQLException e ) { throw e; } return result; }

34

Tìm phòng đặt nhiều (1) String createProcedure = "create procedure SEARCH_HOT_ROOM() " + "begin " + "SELECT a.* FROM tblRoom a ORDER BY " + "(SELECT SUM(DATEDIFF(DAY, b.startDate, b.endDate)) " + "FROM tblBooking b WHERE b.roomId = a.id) DESC;" + "end"; try { Statement stmt = conn.createStatement(); stmt.executeUpdate(createProcedure); } catch (SQLException e ) { throw e; }

Lưu ý: phần code này viết trong phương thức riêng của lớp control, chỉ cần tạo 1 lần, có thể chạy nhiều lần

35

Tìm phòng đặt nhiều (2)public Room[] searchHotRoom()throws SQLException{ Room[] result = null; try { CallableStatement cs = conn.prepareCall("{call SEARCH_HOT_ROOM()}"); ResultSet rs = cs.executeQuery();

if (rs.last()) { result = new Room[rs.getRow()];

rs.beforeFirst(); }

int count = 0; while (rs.next()) { result[count] = new Room(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getString(4)); count++; } } catch (SQLException e ) { throw e; } return result;}

36

Bài tập

Cài đặt tầng giao diện cho bài toán Tích hợp các phương thức đã định nghĩa

vào để được ứng dụng hoàn chỉnh

Questions?