Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Chapter 37 Java Database Programming."— Presentation transcript:

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

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

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

4 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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.

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

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

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

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

9 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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

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

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

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

13 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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.

14 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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.

15 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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));

16 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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

17 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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

18 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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

19 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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) );

20 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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;

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

22 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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';

23 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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);

24 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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';

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

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

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

28 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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

29 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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 jdbc:oracle:thin:@hostname:port#:oracleDBSID 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 ("jdbc:oracle:thin:@liang.armstrong.edu:1521:orcl", "scott", "tiger"); See Supplement IV.D for creating an ODBC data source

30 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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'");

31 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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));

32 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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(); }

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

34 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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.

35 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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

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

37 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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

38 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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

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

40 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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.

41 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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.

42 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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.

43 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 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();

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


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

Similar presentations


Ads by Google