Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

Lp trnh mng

Java kt ni c s d liu
Ging vin: TS. Nguyn Mnh Hng
Hc vin Cng ngh Bu chnh Vin thng (PTIT)

Ni dung

Kt ni vi DB bng JDBC Chun b cu lnh QSL Ly kt qu ra x l Lm vic vi transaction Bi tp

Kt ni DB bng JDBC

Kt ni bng 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";

Kt ni bng 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";

Chun b cu lnh SQL

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

Dng Statement (2)


try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); }catch(ClassNotFoundException e) { e.printStackTrace(); }catch(SQLException e) { e.printStackTrace(); }

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

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

10

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

11

Ly d liu ra

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

13

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

14

Lm vic vi Transaction

iu khin 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); } }

16

iu khin 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();

17

iu khin 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); } }

18

V d: Bi ton qun l t phng khch sn

Bi ton

Mt khch sn (id, tn, a ch, s sao, m t) c nhiu phng (id, hng phng, m t) Mi phng c th c t bi nhiu khch hng (id, tn, m t) ti nhiu thi im khc nhau Mi khch hng c th t nhiu phng ti nhiu thi im khc nhau Mi khch hng ch 1 phng ti 1 thi im nht nh, xc nh 1 gi xc nh Khch hng ch c th t phng nu phng cn trng trong sut thi gian khch hng mun t Khi tr phng, nhn vin in phiu thanh ton bao gm tn khch sn, tn khch hng, s phng, hng phng, ngy n, ngy i v tng s tin thanh ton

20

Yu cu

Thit k cc bng CSDL cho bi ton nh ngha cc lp thc th cho bi ton nh ngha phng thc thm mt phng khch sn vo CSDL nh ngha phng thc tm kim danh sch phng trng trong mt khong thi gian xc nh nh ngha phng thc cho php 1 khch hng t mt phng trong mt thi gian xc nh nh ngha phng thc tnh doanh thu ca khch sn trong mt thi gian xc nh nh ngha phng thc lit k danh sch cc phng c t l khch hng t cao nht trong nm

21

Thit k CSDL (1)

Trc ht cn c 3 bng:

tblHotel: id, name, level, description tblRoom: id, type, description tblCustomer: id, name, username, password, role, description Nhn xt:

1 khch sn c nhiu phng, 1 phng ch trong 1 khch sn quan h gia bng tblHotel v tblRoom l 1-n 1 khch hng t nhiu phng, 1 phng cng c nhiu ngi t quan h gia tblRoom v tblCustomer l n-n, phi chun ha

To thm mt bng t ch chi tit tblBooking: idRoom, idCustomer, startDate, endDate, price, description quan h gia tblRoom v tblBooking l 1-n (mt phng c nhiu ln t), v gia tblCustomer v tblBooking cng l 1-n (mt ngi c nhiu ln t)

22

Thit k CSDL (2)

23

Cc lp thc th (1)

Trc ht cn c 4 lp:

Hotel: id, name, level, description, listRoom Room: id, type, description Customer: id, name, username, password, role, description Booking: id, room, customer, startDate, endDate, price, description Nhn xt:

1 khch sn c nhiu phng thuc tnh listRoom c dng mt mng cc i tng kiu Room 1 phiu t phng c 1 phng thuc tnh room c dng mt i tng kiu Room 1 phiu t phng c 1 khch hng thuc tnh customer c dng mt i tng kiu Customer

24

Cc lp thc th (2)

25

Thm phng (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; } Lu : phn code ny vit trong phng thc ring ca lp control, ch cn to 1 ln, c th chy nhiu ln

26

Thm phng (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; } } Lu : y l phng thc ca lp control

27

Tm phng trng (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; }

28

Tm phng trng (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; }

29

t phng (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; } Lu : phn code ny vit trong phng thc ring ca lp control, ch cn to 1 ln, c th chy nhiu ln

30

t phng (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; } } Lu : y l phng thc ca lp control

31

Tnh 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; } Lu : phn code ny vit trong phng thc ring ca lp control, ch cn to 1 ln, c th chy nhiu ln

32

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

33

Tm phng t nhiu (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; } Lu : phn code ny vit trong phng thc ring ca lp control, ch cn to 1 ln, c th chy nhiu ln

34

Tm phng t nhiu (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; }

35

Bi tp

Ci t tng giao din cho bi ton Tch hp cc phng thc nh ngha vo c ng dng hon chnh

36

Questions?

You might also like