Download presentation
Presentation is loading. Please wait.
Published byEsther Houston Modified over 9 years ago
1
CS 157B: Database Management Systems II January 28 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak www.cs.sjsu.edu/~mak
2
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 2 Form Project Teams 3 students each. Pick a team name. Each team member will get the same score for each team project. Teams will last the entire semester. Choose your team members wisely! Someone from each team send me: Your team name Name and email address of each team member _
3
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 3 MySQL Popular open-source relational database management system (RDBMS). The M in LAMP (Linux+Apache+MySQL+PHP) or Perl or Python Now part of Oracle. Download from http://www.mysql.org/http://www.mysql.org/
4
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 4 The MySQL Workbench MySQL Workbench features Manage databases and database connections. Edit, execute, and save SQL scripts. Forward- and reverse-engineering Generate an ER diagram from an existing database. Manually create an ER diagram. Automatically generate a database from the diagram. Replaces the older MySQL Administrator and MySQL Query Browser tools. Open-source version of some very expensive commercial database design and management tools (such as ERWin Data Modeler). Download from http://dev.mysql.com/downloads/http://dev.mysql.com/downloads/ Demo
5
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 5 Take roll
6
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 6 JDBC Use the JDBC (Java Database Connectivity) API in the java.sql package to make your Java program communicate with a database. Requires the use of a database driver. For MySQL, download Connector/J from http://dev.mysql.com/downloads/connector/j/ http://dev.mysql.com/downloads/connector/j/ Jar file: mysql-connector-java-5.1.12-bin.jar
7
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 7 JDBC Connection Make a connection to the database using a URL, username, and password. Example: import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException;... private static String DB_URL = "jdbc:mysql://localhost:3306/school"; private static String USERNAME = "root"; private static String PASSWORD = "sesame";... Connection conn = DriverManager.getConnection( DB_URL, USERNAME, PASSWORD); Different URL format for an Oracle database.
8
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 8 JDBC Query Create a statement and then generate a result set by executing a query. Example: String QUERY = "SELECT * FROM teacher"; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(QUERY); _
9
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 9 Iterate over a JDBC Result Set Example: ResultSet rs = stmt.executeQuery(QUERY); int id; String lastName; String firstName; while (rs.next()) { id = rs.getInt("id"); lastName = rs.getString("last"); firstName = rs.getString("first");... } IdLastFirst 7003RogersTom 7008ThompsonArt 7012LaneJohn 7051FlynnMabel Teacher Instead of the database field names, you can use 1, 2, 3,...
10
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 10 Object-Relational Mapping Create Java objects from relational database tables. Example: public class Teacher { int id; String lastName; String firstName; }... while (rs.next()) { Teacher teacher = new Teacher(rs.getInt("id"), rs.getString("last"), rs.getString("first"));... } A better way is to use Hibernate to automate object-relational mapping between a Java program and a relational database.
11
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 11 SQL Query Example Who are John Lane’s students? IdLastFirst 1001DoeJohn 1005NovakTim 1009KleinLeslie 1014JaneMary 1021SmithKim CodeTeacher_idSubjectRoom 9087008Data structures114 9267003Java programming101 9317051Compilers222 9517012Software engineering210 9747012Operating systems109 Student_idClass_code 1001926 1001951 1001908 1005974 1005908 1014931 1021926 1021974 1021931 SELECT student.first, student.last, subject FROM student, teacher, class, student_class WHERE teacher.last = 'Lane' AND teacher.first = 'John' AND teacher_id = teacher.id AND code = class_code AND student.id = student_id ORDER BY subject, student.last +-------+-------+----------------------+ | first | last | subject | +-------+-------+----------------------+ | Tim | Novak | Operating systems | | Kim | Smith | Operating systems | | John | Doe | Software engineering | +-------+-------+----------------------+ IdLastFirst 7003RogersTom 7008ThompsonArt 7012LaneJohn 7051FlynnMabel Teacher StudentClass Student_Class
12
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 12 JDBC Prepared Statement Putting a query statement in a loop is inefficient, because the database server has to reparse the statement and build an execution plan each time, even if the statement doesn’t change. Use a prepared statement instead. Example: String query = "SELECT student.first, student.last, subject " + "FROM student, teacher, class, student_class " + "WHERE teacher.last = ? AND teacher.first = ? " + "AND teacher_id = teacher.id " + "AND code = class_code AND student.id = student_id " + "ORDER BY subject, student.last"; PreparedStatement ps = conn.prepareStatement(query); Note the two ? parameters.
13
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 13 JDBC Prepared Statement You can do repeated queries on different teachers by using a prepared statement and parameter substitution. Example: for (Teacher teacher : teachers) { String lastName = teacher.getLastName(); String firstName = teacher.getFirstName(); ps.setString(1, lastName); ps.setString(2, firstName); ResultSet rs = ps.executeQuery(); while (rs.next()) {... } Count the ?’s from 1, not 0.
14
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 14 JDBC Result Set Metadata Each result set has metadata that contains useful information about the query. number of columns column labels etc. Example: ResultSet rs = ps.getResultSet(); ResultSetMetaData rsmd = rs.getMetaData();... int colCount = rsmd.getColumnCount(); String label1 = rsmd.getColumnLabel(1); String label2 = rsmd.getColumnLabel(2);
15
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 15 Database Record Insert, Update, and Delete There are SQL statements to insert, update, and delete records. Three separate examples: INSERT INTO teacher (id, last, first) VALUES (7088, 'Mak', 'Ron'), (7090, 'Wilson', 'Brian') UPDATE teacher SET first = 'Ronald' WHERE first = 'Ron' DELETE FROM teacher WHERE id = 7090 JDBC API: Use the executeUpdate() method of a statement or a prepared statement object to modify the database (insert, update, or delete). The return value is the number of records that were affected. This can update multiple records!
16
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 16 JDBC Example: Database Record Insert Method executeUpdate() returns the number of records that were inserted. _ String insert = "INSERT INTO teacher (id, last, first)" + "VALUES (7088, 'Mak', 'Ron'), " + " (7090, 'Wilson', 'Brian') "; Statement stmt = conn.createStatement(); int rowCount = stmt.executeUpdate(insert);
17
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 17 JDBC Example: Database Record Update String update = "UPDATE teacher" + "SET first = 'Robert'" + "WHERE first LIKE= 'Ron%'"; rowCount = stmt.executeUpdate(update); In any WHERE clause, LIKE allows wild cards in the string pattern. % matches zero or more characters. 'Ron%' matches 'Ron' and 'Ronald' _ matches any single character. '_onald' matches 'Ronald' and 'Donald‘ Method executeUpdate() returns the number of records that were changed.
18
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 18 JDBC Example: Database Record Delete Method executeUpdate() returns the number of records that were deleted. _ String delete = "DELETE FROM teacher" + "WHERE first = 'Robert'"; rowCount = stmt.executeUpdate(delete);
19
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 19 Closing JDBC Objects When you’re done with them, don’t forget to close your JDBC statement, prepared statement, and result set objects, and especially the database connection object. Examples: stmt.close(); ps.close(); rs.close(); conn.close(); Note that most JDBC API calls throw an exception if an error occurred, generally SQLException, which you’ll need to catch. A database server can support only a limited number of connections. Demo
20
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 20 Data Access Layer Databases and SQL are extremely powerful. Let MySQL do what it’s good at doing, and let Java do what it’s good at doing. For example, don’t write Java code to sort the records – let the database do that! Add a data access layer to your application. The data access layer contains all the JDBC API calls and manages the database connection pool. Keep the rest of your application loosely-coupled from the database code. With object-relational mapping, the rest of your application deals only with objects, not result sets. _
21
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 21 APPLICATION Multilayered Application Architecture Presentation Layer GUI Objects Application Layer Application Logic Objects Data Access Layer Fetch and Store Model Objects Database
22
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 22 Shortcomings of JDBC Java programmers must understand relational databases. The database is very visible. The Java programmer must know SQL. JDBC is not object-oriented. A Java program accesses field values individually from a result set. You need statements to create Java objects from the result set values. _
23
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 23 Object-Relational Mapping Goal: Overcome the paradigm mismatch between relational data from an RDBMS and object-oriented programming. Object-oriented languages such as Java would much rather deal with classes and objects. Java programmers do not want to write SQL. Java programmers do not want to want to deal with database concepts such as one-to-many, one-to-many, many-to-many, etc. Java programmers do not want to understand normalization. _
24
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 24 Object-Relational Mapping Solution: Add a layer of software between the database and the Java application that does object-relational mapping. Relational data being read from the database are automatically converted to objects. Objects being persisted (saved) to the database are automatically converted to relational data. The Java application manipulates objects (create, update, search, delete) and these operations are automatically translated into the corresponding database operations. Database platform independence. The Java programmer can mostly forget that there is an underlying database. _
25
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 25 Hibernate A very popular open-source object-relational persistence and query service for Java. Download from http://www.hibernate.org/http://www.hibernate.org/ Replace the JDBC API with the Hibernate API. Java annotations describe in detail the mapping between the Java classes and the relational database tables. _
26
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 26 Hibernate: Student Note the annotations. Provide metadata for the Java compiler and the Java run time. @Entity public class Student { private long id; private String firstName; private String lastName; public Student() {} public Student(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; }... }
27
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 27 Hibernate: Student @Entity public class Student {... @Id @GeneratedValue @Column(name="id") public long getId() { return id; } public void setId(long id) { this.id = id; } @Column(name="first_name") public String getFirstName() { return firstName; } public void setFirstName(String name) { this.firstName = name; } @Column(name="last_name") public String getLastName() { return lastName; } public void setLastName(String name) { this.lastName = name; }... }
28
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 28 Hibernate: Student Import Java packages: Hibernate Hibernate annotations Log4J package schooldemo; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Column; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.tool.hbm2ddl.SchemaExport;
29
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 29 Hibernate: Student Main method (for testing) public static void main(String args[]) { // Configure Hibernate and add the Student class. AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass(Student.class); config.configure(); // Create the database table. (new SchemaExport(config)).create(true, true); // Create a session. SessionFactory factory = config.buildSessionFactory(); Session session = factory.openSession();... }
30
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 30 Hibernate: Student public static void main(String args[]) {... // Create a session. SessionFactory factory = config.buildSessionFactory(); Session session = factory.openSession(); // Load the Student table in a transaction. Transaction tx = session.beginTransaction(); { session.save(new Student("Mary", "Jane")); session.save(new Student("Kim", "Smith")); session.save(new Student("John", "Doe")); session.save(new Student("Tim", "Novak")); session.save(new Student("Leslie", "Klein")); } tx.commit(); session.close(); } Main method
31
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 31 hibernate.cfg.xml Hibernate configuration file Modify as necessary. Must be in your application’s classpath. <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> com.mysql.jdbc.Driver jdbc:mysql://localhost/school_demo root sesame org.hibernate.dialect.MySQL5Dialect true
32
Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 32 log4j.properties Just copy the sample file. Also must be in your classpath. Demo
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.