CS 157B: Database Management Systems II January 28 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.

Slides:



Advertisements
Similar presentations
Basic JDBC Celsina Bignoli What is JDBC Industry standard for database- connectivity between the Java language and a wide range of.
Advertisements

CS 185C/286: The History of Computing October 31 Class Meeting Department of Computer Science San Jose State University Fall 2011 Instructor: Ron Mak
15-Jun-15 JDBC. JDBC is a Sun trademark It is often taken to stand for Java Database Connectivity Java is very standardized, but there are many versions.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 32 Java Database.
1 C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California
UFCE4Y UFCE4Y-20-3 Components and Services Julia Dawson.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Java Database Connectivity (JDBC) Francisco Pajaro Saul Acosta Nahum Quezada Manuel Rubio.
1 Java Database Connection (JDBC) There are many industrial-strength DBMS's commercially available in the market. Oracle, DB2, and Sybase are just a few.
CS 160: Software Engineering November 10 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
Java Database Connectivity (JDBC) Introduction to JDBC JDBC is a simple API for connecting from Java applications to multiple databases. Lets you smoothly.
JDBC and Hibernate Joshua Scotton. Connecting to Relational DBs.
CS 160: Software Engineering October 8 Class Meeting
CS 157B: Database Management Systems II January 30 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
CS 157B: Database Management Systems II April 29 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
MySQL, Java, and JDBC CSE 3330 Southern Methodist University.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
JAVA Database Access. JDBC The Java Database Connectivity (JDBC) API is the industry standard for database- independent connectivity between the Java.
CS 174: Web Programming September 23 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
CS 174: Web Programming September 21 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
CS 157B: Database Management Systems II February 6 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
CS 160: Software Engineering November 5 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
CS 157B: Database Management Systems II February 4 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
CS 160: Software Engineering October 1 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
JDBC. JDBC stands for Java Data Base Connectivity. JDBC is different from ODBC in that – JDBC is written in Java (hence is platform independent, object.
CS 160: Software Engineering October 15 Class Meeting
CS 160: Software Engineering October 6 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
Hibernate 3.0. What is Hibernate Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it.
Chapter 8 Databases.
Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
CS 174: Web Programming October 14 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
JDBC CS 260 Database Systems. Overview  Introduction  JDBC driver types  Eclipse project setup  Programming with JDBC  Prepared statements  SQL.
CSI 3125, Preliminaries, page 1 JDBC. CSI 3125, Preliminaries, page 2 JDBC JDBC stands for Java Database Connectivity, which is a standard Java API (application.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
Basics of JDBC.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
Web Programming Assistant Professor Xiaozhong Liu
CS 174: Web Programming November 2 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
1 Download current version of Tomcat from: g/tomcat/ g/tomcat/ Install it in: C:\Program Files\Apache.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
CS422 Principles of Database Systems Object-Relational Mapping (ORM) Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA (I) Chengyu Sun California State University, Los Angeles.
CS 160 and CMPE/SE 131 Software Engineering March 10 Class Meeting Department of Computer Science Department of Computer Engineering San José State University.
CS 160 and CMPE/SE 131 Software Engineering March 15 Class Meeting Department of Computer Science Department of Computer Engineering San José State University.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java program to connect to any database.
CS 157B: Database Management Systems II January 23 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
Database Programming Basic JDBC Programming Concepts.
CS3220 Web and Internet Programming Database Access with JDBC
Java Access to RDB Relational databases (RDBs) dominate today, due to:
Chengyu Sun California State University, Los Angeles
JDBC 15-Apr-18.
Advanced Web Automation Using Selenium
JDBC 21-Aug-18.
HW#4 Making Simple BBS Using JDBC
JDBC.
Introduction to Server-Side Web Development using JSP and Databases
JDBC 15-Nov-18.
CMPE/SE 131 Software Engineering March 9 Class Meeting
JDBC API.
JDBC Example.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

CS 157B: Database Management Systems II January 28 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak

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 address of each team member _

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

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 Demo

Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 5 Take roll

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 Jar file: mysql-connector-java bin.jar

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.

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); _

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,...

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.

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 Data structures Java programming Compilers Software engineering Operating systems109 Student_idClass_code 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

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.

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.

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

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!

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

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.

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

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

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. _

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

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. _

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. _

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. _

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  Replace the JDBC API with the Hibernate API.  Java annotations describe in detail the mapping between the Java classes and the relational database tables. _

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

Department of Computer Science Spring 2013: January 28 CS 157B: Database Management Systems II © R. Mak 27 Hibernate: public class @Column(name="id") public long getId() { return id; } public void setId(long id) { this.id = id; public String getFirstName() { return firstName; } public void setFirstName(String name) { this.firstName = name; public String getLastName() { return lastName; } public void setLastName(String name) { this.lastName = name; }... }

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;

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

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

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" " com.mysql.jdbc.Driver jdbc:mysql://localhost/school_demo root sesame org.hibernate.dialect.MySQL5Dialect true

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