Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Chapter 37 Java Database Programming.

Slides:



Advertisements
Similar presentations
Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
Advertisements

Database Management Systems, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
Java Database Connectivity (JDBC). 2/24 JDBC (Java DataBase Connectivity) - provides access to relational database systems JDBC is a vendor independent.
SQL Lecture 10 Inst: Haya Sammaneh. Example Instance of Students Relation  Cardinality = 3, degree = 5, all rows distinct.
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
CSE470 Software Engineering Fall Database Access through Java.
Java database Programming JDBC Trademarked name of a Java API that supports Java programs that access relational databases Stand for Java DataBase Connectivity.
1 Foundations of Software Design Lecture 27: Java Database Programming Marti Hearst Fall 2002.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 37 Java Database Programming.
JAVA JDBC JAVA JDBC Java Database Programming Lamiaa Said.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
1 CSC 440 Database Management Systems JDBC This presentation uses slides and lecture notes available from
Accessing Databases with JDBC. Introduction to JDBC JDBC provides a standard library for accessing databases by using the JDBC API. JDBC standardizes.
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
Think Possibility Integrating Web Applications With Databases.
Helena Pomezná, ciz034 St. skupina: L392 FEI, VŠB-TUO Ak. rok. 2002/2003 Download:
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 8 Object Oriented Programming in Java Advanced Topics Java Database.
CSE470 Software Engineering Fall Database Access through Java.
Intro to JDBC To effectively use Java Data Base Connectivity we must understand: 1.Relational Database Management Systems (RDBMS) 2.JDBC Drivers 3.SQL.
Java Database Connectivity (JDBC) Introduction to JDBC JDBC is a simple API for connecting from Java applications to multiple databases. Lets you smoothly.
Database Programming in Java Corresponds with Chapter 32, 33.
Java Utility Classes CS 21b. Some Java Utility Classes Vector Hashtable StringTokenizer * import java.util.*;
CIS 270—Application Development II Chapter 25—Accessing Databases with JDBC.
Relational Database Management Systems. A set of programs to manage one or more databases Provides means for: Accessing the data Inserting, updating and.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 38 Advanced Java Database.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 37 Java Database.
Connecting to Oracle using Java November 4, 2009 David Goldschmidt, Ph.D. David Goldschmidt, Ph.D.
FALL 2004CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
1 Chapter 25 Java Database Programming. 2 Objectives F To understand the concept of database and database management systems (§25.2). F To understand.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
MySQL and JDBC Tutorial ECT 7130 Hong Cheng. Supplement on MySQL ement/Supplement4bMySQL.pdf.
Copyright © 2002 ProsoftTraining. All rights reserved. Building Database Client Applications Using JDBC 2.0.
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.
JDBC CS 124. JDBC Java Database Connectivity Database Access Interface provides access to a relational database (by allowing SQL statements to be sent.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
DATABASE CONNECTIVITY TO MYSQL. Introduction =>A real life application needs to manipulate data stored in a Database. =>A database is a collection of.
Chapter 25 Java Database Programming
DataBases and SQL INFSY 547 Spring Course Wrap Up April 12: Complete Work on Servlets Review of Team Projects Close of Portfolio Work April 19:
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 22 - SQL, MySQL, DBI and ADO Outline 22.1 Introduction 22.2 Relational Database Model 22.3 Relational.
JDBC and SQLJ CIS 612 Spring JDBC JDBC is an API that enables database access from Java programs JDBC for DB access provides ◦ Portability across.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
Basics of JDBC Session 14.
1 Principles of Database Systems With Internet and Java Applications Today’s Topic Chapter 8: Applications Programming for Relational Databases Instructor’s.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L12_Oracle10g_JDBC 1 Application Development (JDBC)
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
1 CS122A: Introduction to Data Management Lecture #4 (E-R  Relational Translation) Instructor: Chen Li.
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
Note: To complete the examples in this section you need access to a database!! Most of the examples work for any database with JDBC drivers. However, connecting.
Lec - 14.
CS320 Web and Internet Programming SQL and MySQL
JDBC Database Management Database connectivity
Chapter 34 Java Database Programming
CS320 Web and Internet Programming Database Access with JDBC
SQL in Oracle.
UNIT-2 Java Database Programming
JDBC.
Interacting with Database
Chapter 22 - SQL, MySQL, DBI and ADO
Bolat Azamat, Kim Dongmin
CS3220 Web and Internet Programming SQL and MySQL
CS3220 Web and Internet Programming SQL and MySQL
Java Chapter 6 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 37 Java Database Programming 1

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved What is a Database System? e.g., Access, MySQL, Oracle, and MS SQL Server 2

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Database Application Systems 3

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Relational Databases Most of today’s database systems are relational database systems, based on the relational data model. Components: 4 F Structure – data representation F Integrity – constraints F Language – for accessing and manipulating data.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Course Table 5

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Student Table 6

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Enrollment Table 7

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Table vs. File NOTE: Table (relation) is not the same as file. Most relational database systems store multiple tables in a file. 8

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Integrity Constraints Integrity constraints impose conditions that the relations must satisfy.  intra-relational constraints (involve 1 relation)  domain constraint  primary key constraint  inter-relational (involve more than 1 relation)  foreign key constraint. 9

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Domain Constraints domain constraint 10 specify the permissible values for an attribute.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Primary Key Constraints Primary key constraint 11 Used to identify records in a relation

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Foreign Key Constraints Foreign key constraint 12 Define relationships between tables

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Superkey Key Candidate key Primary key 13 A superkey is an attribute or a set of attributes that uniquely identify the relation. No two tuples have the same values on the superkey. A relation consists of a set of distinct tuples. The set of all attributes in the relation forms a superkey.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Key and Candidate Key Superkey Key Candidate key Primary key 14 A key K is a minimal superkey, meaning that any proper subset of K is not a superkey. It is possible that a relation has several keys. In this case, each of the keys is called a candidate key.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Primary Key Superkey Key Candidate key Primary key 15 The primary key is a candidate key designated by the database designer. Often used to identify tuples in a relation. create table Course( subjectCode char(4), courseNumber int, title varchar(50), numOfCredits int constraint greaterThanOne check (numOfCredits >= 1), primary key (subjectCode, courseNumber));

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Foreign Key Example create table Enrollment ( ssn char(9), courseId char(5), dateRegistered date, grade char(1), primary key (ssn, courseId), foreign key (ssn) references Student, foreign key (courseId) references Course ); 16

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Foreign Key Discussion, cont. A foreign key is not necessarily the primary key or part of the primary in the relation. The referencing relation and the referenced relation may be the same table. (supervisorId is a foreign key in Faculty that references facultyId in Faculty) Foreign key and its referenced primary key can have different names, as long as they have the same domain. 17

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved SQL SQL: Structured Query Language  To access database data  To manipulate data  Universal language for accessing relational database systems  Application programs may allow users to access database without directly using SQL, since the underlying applications use SQL. 18

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Examples of simple SQL statements Create table Drop table Describe table Select Insert Delete Update 19 create table Course ( courseId char(5), subjectId char(4) not null, courseNumber integer, title varchar(50) not null, numOfCredits integer, primary key (courseId) ); create table Student ( ssn char(9), firstName varchar(25), mi char(1), lastName varchar(25), birthDate date, street varchar(25), phone char(11), zipCode char(5), deptId char(4), primary key (ssn) );

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Examples of simple SQL statements Create table Drop table Describe table Select Insert Delete Update 20 drop table Enrollment; drop table Course; drop table Student;

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Examples of simple SQL statements Create table Drop table Describe table Select Insert Delete Update 21 describe Course; -- Oracle

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Examples of simple SQL statements Create table Drop table Describe table Select Insert Delete Update 22 select firstName, mi, lastName from Student where deptId = 'CS'; select firstName, mi, lastName from Student where deptId = 'CS' and zipCode = '31411'; select * from Student where deptId = 'CS' and zipCode = '31411';

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Examples of simple SQL statements Create table Drop table Describe table Select Insert Delete Update 23 insert into Course (courseId, subjectId, courseNumber, title) values ('11113', 'CSCI', '3720', 'Database Systems', 3);

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Examples of simple SQL statements Create table Drop table Describe table Select Insert Update Delete 24 update Course set numOfCredits = 4 where title = 'Database Systems';

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Examples of simple SQL statements Create table Drop table Describe table Select Insert Update Delete 25 delete Course where title = 'Database System';

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved The Architecture of JDBC 26

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved The JDBC Interfaces Loading drivers Establishing connections Creating and executing statements Processing ResultSet 27

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Developing JDBC Programs Loading drivers Establishing connections Creating and executing statements Processing ResultSet 28 Statement to load a driver: Class.forName("JDBCDriverClass"); A driver is a class. For example: Database Driver Class Source Access sun.jdbc.odbc.JdbcOdbcDriver Already in JDK MySQL com.mysql.jdbc.Driver Website Oracle oracle.jdbc.driver.OracleDriver Website The JDBC-ODBC driver for Access is bundled in JDK. MySQL driver class is in mysqljdbc.jar Oracle driver class is in classes12.jar To use the MySQL and Oracle drivers, you have to add mysqljdbc.jar and classes12.jar in the classpath using the following DOS command on Windows: classpath=%classpath%;c:\book\mysqljdbc.jar;c:\book\classes12.jar

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Developing JDBC Programs Loading drivers Establishing connections Creating and executing statements Processing ResultSet 29 Connection connection = DriverManager.getConnection(databaseURL); Database URL Pattern Access jdbc:odbc:dataSource MySQL jdbc:mysql://hostname/dbname Oracle Examples: For Access: Connection connection = DriverManager.getConnection ("jdbc:odbc:ExampleMDBDataSource"); For MySQL: Connection connection = DriverManager.getConnection ("jdbc:mysql://localhost/test"); For Oracle: Connection connection = DriverManager.getConnection "scott", "tiger"); See Supplement IV.D for creating an ODBC data source

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Developing JDBC Programs Loading drivers Establishing connections Creating and executing statements Processing ResultSet 30 Creating statement: Statement statement = connection.createStatement(); Executing statement (for update, delete, insert): statement.executeUpdate ("create table Temp (col1 char(5), col2 char(5))"); Executing statement (for select): // Select the columns from the Student table ResultSet resultSet = statement.executeQuery ("select firstName, mi, lastName from Student where lastName " + " = 'Smith'");

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Developing JDBC Programs Loading drivers Establishing connections Creating and executing statements Processing ResultSet 31 Executing statement (for select): // Select the columns from the Student table ResultSet resultSet = stmt.executeQuery ("select firstName, mi, lastName from Student where lastName " + " = 'Smith'"); Processing ResultSet (for select): // Iterate through the result and print the student names while (resultSet.next()) System.out.println(resultSet.getString(1) + " " + resultSet.getString(2) + ". " + resultSet.getString(3));

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Simple JDBC Example 32 import java.sql.*; public class SimpleJdbc { public static void main(String[] args) throws SQLException, ClassNotFoundException { // Load the JDBC driver Class.forName("com.mysql.jdbc.Driver"); System.out.println("Driver loaded"); // Establish a connection Connection connection = DriverManager.getConnection ("jdbc:mysql://localhost/test"); System.out.println("Database connected"); // Create a statement Statement statement = connection.createStatement(); // Execute a statement ResultSet resultSet = statement.executeQuery ("select firstName, mi, lastName from Student where lastName " + " = 'Smith'"); // Iterate through the result and print the student names while (resultSet.next()) System.out.println(resultSet.getString(1) + "\t" + resultSet.getString(2) + "\t" + resultSet.getString(3)); // Close the connection connection.close(); }

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Creating ODBC Data Source Please follow the steps in Supplement on the Companion Website to create an ODBC data source on Windows. 33

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Example: Accessing Database from Java Applets This example demonstrates connecting to a database from a Java applet. The applet lets the user enter the SSN and the course ID to find a student’s grade. 34 FindGrade Run NOTE: To run this program from here, you need: 1. To have a MySQL database setup just like the one in the text. 2. Set MySQL JDBC driver in the classpath.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Processing Statements Once a connection to a particular database is established, it can be used to send SQL statements from your program to the database. JDBC provides the Statement, PreparedStatement, and CallableStatement interfaces to facilitate sending statements to a database for execution and receiving execution results from the database. 35

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Processing Statements Diagram 36

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved execute, executeQuery, executeUpdate Methods for executing SQL statements:  execute  executeQuery (single result set)  executeUpdate (0 or 1 update counts) Parameters: string containing a SQL statement, passed to database for execution Use execute if multiple result sets, multiple update counts, or a combination of result sets and update counts are produced. 37

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Retrieving Database Metadata Database metadata: information that describes the database itself. JDBC includes  DatabaseMetaData interface for obtaining database wide information  ResultSetMetaData interface for descriptive information on a specific ResultSet. 38

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved DatabaseMetaData methods can be divided into three groups:  retrieve general information:  find database capabilities  get object descriptions 39 Database Metadata, cont.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved DatabaseMetaData methods can be divided into three groups:  retrieve general information:  URL  username  product version  driver name / version  available functions / data types  find database capabilities  get object descriptions 40 Database Metadata, cont.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved DatabaseMetaData methods can be divided into three groups:  retrieve general information:  find database capabilities  does the database supports GROUP BY ?  is add column option valid in ALTER TABLE?  supported types of SQL grammar  get object descriptions 41 Database Metadata, cont.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved DatabaseMetaData methods can be divided into three groups:  retrieve general information:  find database capabilities  get object descriptions  describe table  describe view  describe procedure 42 Database Metadata, cont.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Examples 43 DatabaseMetaData dbMetaData = connection.getMetaData(); System.out.println("database URL: " + dbMetaData.getURL()); System.out.println("database username: " + dbMetaData.getUserName()); System.out.println("database product name: " + dbMetaData.getDatabaseProductName()); System.out.println("database product version: " + dbMetaData.getDatabaseProductVersion()); System.out.println("JDBC driver name: " + dbMetaData.getDriverName()); System.out.println("JDBC driver version: " + dbMetaData.getDriverVersion()); System.out.println("JDBC driver major version: " + new Integer(dbMetaData.getDriverMajorVersion())); System.out.println("JDBC driver minor version: " + new Integer(dbMetaData.getDriverMinorVersion())); System.out.println("Max number of connections: " + new Integer(dbMetaData.getMaxConnections())); System.out.println("MaxTableNameLentgh: " + new Integer(dbMetaData.getMaxTableNameLength())); System.out.println("MaxColumnsInTable: " + new Integer(dbMetaData.getMaxColumnsInTable())); connection.close();

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Sample Run 44