43
Database Programming Database Programming in Java in Java Corresponds with Chapter 32, 33

Database Programming in Java Corresponds with Chapter 32, 33

Embed Size (px)

Citation preview

Page 1: Database Programming in Java Corresponds with Chapter 32, 33

Database Programming Database Programming in Javain Java

Corresponds with Chapter 32, 33

Page 2: Database Programming in Java Corresponds with Chapter 32, 33
Page 3: Database Programming in Java Corresponds with Chapter 32, 33

The Entity-Relationship (ER) The Entity-Relationship (ER) ModelModel

The most common way of representing The most common way of representing the world for the purpose of database the world for the purpose of database design and analysis. design and analysis.

Graphical depiction of things in the Graphical depiction of things in the world (entities) and the relationships world (entities) and the relationships between them (relationships). between them (relationships).

Page 4: Database Programming in Java Corresponds with Chapter 32, 33

Major Data Elements in ER Major Data Elements in ER ModelsModels

ENTITYENTITY: Person, Place, Thing, Event about : Person, Place, Thing, Event about which data must be keptwhich data must be kept represented by a RECORD (row) in a TABLErepresented by a RECORD (row) in a TABLE

ATTRIBUTEATTRIBUTE: Description of a Particular entity: Description of a Particular entity represented by a FIELD (column) of the RECORDrepresented by a FIELD (column) of the RECORD

RELATIONSHIPSRELATIONSHIPS: Description of how Entities : Description of how Entities interact with each otherinteract with each other 1:1 , 1:N (one-to-many), N:M (many-to-many)1:1 , 1:N (one-to-many), N:M (many-to-many) Represented by associations between Primary and Represented by associations between Primary and

Foreign keys (identifiers)Foreign keys (identifiers)

Page 5: Database Programming in Java Corresponds with Chapter 32, 33

ER Diagram of Employee ER Diagram of Employee DatabaseDatabase

Entities in boxes

Relationships in diamonds

Employees

Departments

JobTypes

Projects

1 | N

1 | N

M | N

1 | N

Page 6: Database Programming in Java Corresponds with Chapter 32, 33

Entities in Employee Entities in Employee DatabaseDatabase

Employees - data about people in the Employees - data about people in the companycompany

Departments - data about the Departments - data about the organizational unitsorganizational units

JobTypes - data about the work JobTypes - data about the work classificationsclassifications

Projects - data about the current Projects - data about the current projects underwayprojects underway

Page 7: Database Programming in Java Corresponds with Chapter 32, 33

Relationships in Employee Relationships in Employee DatabaseDatabase

Each Each departmentdepartment has many has many employeesemployees, but , but each employee works for only one department each employee works for only one department (1:N)(1:N)

There are many There are many employeesemployees of a given of a given job typejob type, , but each employee has only one job title (1:N)but each employee has only one job title (1:N)

An An employee who is a manageremployee who is a manager has many has many employees under her, but each employees under her, but each employeeemployee has has only one manager to report to (1:N)only one manager to report to (1:N)

Each Each employeeemployee can be working on several can be working on several projects, and each projects, and each projectproject may have several may have several employees working on it (M:N)employees working on it (M:N)

Page 8: Database Programming in Java Corresponds with Chapter 32, 33

What is a What is a relational relational databasedatabase??

A database in which:A database in which: entity types are represented by TABLES entity types are represented by TABLES

(also called RELATIONS), (also called RELATIONS), specific entities are represented by ROWS specific entities are represented by ROWS

in the TABLE (records)in the TABLE (records) attributes are represented by COLUMNS attributes are represented by COLUMNS

in the TABLE (fields)in the TABLE (fields) relationships between entities are relationships between entities are

represented by associations between represented by associations between primary and foreign keys (identifier fields)primary and foreign keys (identifier fields)

Page 9: Database Programming in Java Corresponds with Chapter 32, 33

ER-Diagram of the tables in ER-Diagram of the tables in the Employee Databasethe Employee Database

8

1

The relationships are implemented via associations between primary keys (shown here in boldface) and foreign keys of tables

M:N relationships require an additional table, called an intersection (or junction) table.

The M:N relationship between Employees and Projects is implemented via the EmployeeProject intersection table.

Page 10: Database Programming in Java Corresponds with Chapter 32, 33

1:N Relationship Between 1:N Relationship Between Departments and Departments and

EmployeesEmployees

The DepartmentID field of the Employees table is a foreign key. It references the DepartmentID field of the Departments table (primary key). In this way, we can see that Sam Smith, Mike Mitri, Alice Friedman, and Brendan Mitri are all in the Payroll department. (DepartmentID = 2).

A department has several employees, but each employee is in only one department.

Page 11: Database Programming in Java Corresponds with Chapter 32, 33

M:N relationship between M:N relationship between Employees and ProjectsEmployees and Projects

The EmployeeProject table is an intersection table that implements the M:N relationship. The EmployeeID field of the EmployeeProject table is a foreign key that references the EmployeeID field of the Employees table. Likewise for the ProjectID fields. Here we see that James Smith is one of the four employees who works on Accounts Payable project. James Smith also works on the Accounts Receivable project.

Each employee can have several projects and each project can have several employees.

Page 12: Database Programming in Java Corresponds with Chapter 32, 33

The SELECT StatementThe SELECT Statement SELECTSELECT is a keyword in the SQL language is a keyword in the SQL language First word in all SQL First word in all SQL queriesqueries (i.e. SQL (i.e. SQL

statements that display database information statements that display database information to the user)to the user)

The DBMS will respond to a SELECT statement The DBMS will respond to a SELECT statement by returning a by returning a result setresult set..

Java has an interface that works with result Java has an interface that works with result sets, called sets, called ResultSetResultSet. Each database vendor . Each database vendor has drivers that implement this interface.has drivers that implement this interface.

Page 13: Database Programming in Java Corresponds with Chapter 32, 33

SQL Statements for Data SQL Statements for Data ModificationModification

INSERTINSERT - adds a new row to a table - adds a new row to a table UPDATEUPDATE - modifies one or more an existing row(s) - modifies one or more an existing row(s) DELETEDELETE - removes one or more existing row(s) - removes one or more existing row(s)

In Java, the In Java, the StatementStatement interface’s interface’s executeUpdate()executeUpdate() method will be used to implement these operations.method will be used to implement these operations.

Page 14: Database Programming in Java Corresponds with Chapter 32, 33
Page 15: Database Programming in Java Corresponds with Chapter 32, 33

JDBCJDBC

Java Data Base ConnectivityJava Data Base Connectivity Provides a connection between a Java Provides a connection between a Java

application or applet and a database application or applet and a database systemsystem

JDBC classes and interfaces available JDBC classes and interfaces available from the from the java.sqljava.sql package package

JDBC is implemented by a JDBC driverJDBC is implemented by a JDBC driver

Page 16: Database Programming in Java Corresponds with Chapter 32, 33

Java Database Connectivity Java Database Connectivity (JDBC)(JDBC)

An set of classes and drivers that allows An set of classes and drivers that allows applications to access data in database applications to access data in database management systems (DBMS) using management systems (DBMS) using Structured Query Language (SQL) as a Structured Query Language (SQL) as a standard for accessing data.standard for accessing data.

Supports Supports interoperabilityinteroperability: a programmer : a programmer can create an JDBC application without can create an JDBC application without targeting a specific data source. Users can targeting a specific data source. Users can add drivers to the application after it is add drivers to the application after it is compiled and shipped.compiled and shipped.

Page 17: Database Programming in Java Corresponds with Chapter 32, 33

Components of JDBCComponents of JDBC

ApplicationApplication - - The program you develop. Calls The program you develop. Calls JDBC functions to submit SQL statements and retrieve JDBC functions to submit SQL statements and retrieve results.results.

Driver ManagerDriver Manager - - Provides access to JDBC Provides access to JDBC drivers.drivers.

JDBC DriverJDBC Driver - - Processes JDBC function calls, Processes JDBC function calls, submits SQL requests to a data source, and returns submits SQL requests to a data source, and returns results to the application.results to the application.

Data sourceData source - - A database and its associated A database and its associated DBMS.DBMS.

Page 18: Database Programming in Java Corresponds with Chapter 32, 33

ApplicationApplication

Driver ManagerDriver Manager

DriverDriver

DataDataSourceSource(MS Access)(MS Access)

DriverDriver

DataDataSourceSource(Oracle)(Oracle)

Page 19: Database Programming in Java Corresponds with Chapter 32, 33

The ApplicationThe Application

Requests connection to a data source.Requests connection to a data source. Sends SQL requests to the data source.Sends SQL requests to the data source. Contains storage areas and data formats for Contains storage areas and data formats for

the results of SQL requests.the results of SQL requests. Requests results.Requests results. Processes errors.Processes errors. Displays data to userDisplays data to user Terminates the connection to the data source.Terminates the connection to the data source.

Page 20: Database Programming in Java Corresponds with Chapter 32, 33

JDBC Driver ManagerJDBC Driver Manager A class in the A class in the java.sqljava.sql package package Loads drivers for the application.Loads drivers for the application. Processes JDBC initialization calls.Processes JDBC initialization calls. Provides entry points to JDBC functions Provides entry points to JDBC functions

for a JDBC driver.for a JDBC driver.

Page 21: Database Programming in Java Corresponds with Chapter 32, 33

JDBC DriverJDBC Driver Typically a DLL Typically a DLL Implements JDBC interfaces and their methods and Implements JDBC interfaces and their methods and

interacts with a data source.interacts with a data source. Each DBMS has its own JDBC driver. Each DBMS has its own JDBC driver. Establishes a connection to a data source.Establishes a connection to a data source. Submits requests to the data source.Submits requests to the data source. Translates data to or from other formats, if Translates data to or from other formats, if

requested by the application.requested by the application. Returns results to the application.Returns results to the application. Formats errors into standard error codes and returns Formats errors into standard error codes and returns

them to the application.them to the application.

Java JDK includes a JDBC driver called the JDBC-ODBC bridgeOther drivers are available from other vendors

See http://developers.sun.com/product/jdbc/drivers for full listing of available drivers from different vendors

Page 22: Database Programming in Java Corresponds with Chapter 32, 33

Data SourcesData Sources

A database and its DBMS product A database and its DBMS product (and any remote operating system (and any remote operating system and network necessary to access and network necessary to access it) client-server capabilitiesit) client-server capabilities

NOTE: Your system’s installed NOTE: Your system’s installed ODBC drivers and recognized data ODBC drivers and recognized data sources can be seen and modified sources can be seen and modified through the through the ODBC Administrator ODBC Administrator Dialog BoxDialog Box available in the Control available in the Control Panel.Panel.

Page 23: Database Programming in Java Corresponds with Chapter 32, 33

JDBC Interfaces JDBC Interfaces ConnectionConnection DatabaseMetaDataDatabaseMetaData DriverDriver ResultSetResultSet ResultSetMetaDatResultSetMetaDat

aa StatementStatement

These are all interfaces(i.e. completely abstract)They are implemented withinthe loaded JDBC driver

A JDBC-compliant driver implements all the functionalityof these interfaces

Boldfaced interfaces will be used in examples and assignment

Page 24: Database Programming in Java Corresponds with Chapter 32, 33

JDBC ClassesJDBC Classes

DateDate DriverManagerDriverManager DriverProperyInfoDriverProperyInfo TimeTime TimeStampTimeStamp TypesTypes

DriverManager will be used in the example and assignment

Page 25: Database Programming in Java Corresponds with Chapter 32, 33

Creating JDBC Applications Creating JDBC Applications in Javain Java

Steps involved:Steps involved: Connect to a data sourceConnect to a data source Perform query and update operations Perform query and update operations

on tables or record setson tables or record sets Close the connection to the data Close the connection to the data

sourcesource

Note: many JDBC operations throw SQLExceptions, soyour application must throw or catch these also

Page 26: Database Programming in Java Corresponds with Chapter 32, 33

Connecting to a DatabaseConnecting to a Database

3 steps:3 steps: load the driverload the driver

use the use the Class.forName(drivername)Class.forName(drivername) method method specify the URL for the data sourcespecify the URL for the data source

JDBC URL format as follows:JDBC URL format as follows: jdbc:<subprotocol>:<subname>jdbc:<subprotocol>:<subname> note: jdbc is always the protocol -- the subprotocol depends note: jdbc is always the protocol -- the subprotocol depends

on type of driver (e.g. odbc) -- the subname is the name of on type of driver (e.g. odbc) -- the subname is the name of the data sourcethe data source

connect to the data sourceconnect to the data source using the using the DriverManager.getConnection(url, DriverManager.getConnection(url,

username,password)username,password) method method

Page 27: Database Programming in Java Corresponds with Chapter 32, 33

Performing QueriesPerforming Queries

Create a Create a StatementStatement instance instance Set up an SQL query in a Set up an SQL query in a StringString (typically an (typically an

SQL SELECT statement)SQL SELECT statement) use the use the StatementStatement class’s class’s executeQuery()executeQuery()

method to obtain the method to obtain the ResultSetResultSet of rows that of rows that match the querymatch the query

Use the Use the ResultSetResultSet class’s class’s next()next() method to method to read the records and the read the records and the ResultSetResultSet class’s class’s get****()get****() methods for obtaining and methods for obtaining and processing dataprocessing data

See the JDBC example

Page 28: Database Programming in Java Corresponds with Chapter 32, 33

Performing UpdatesPerforming Updates

Create a Create a StatementStatement instance instance Set up an SQL statement in a Set up an SQL statement in a StringString

(typically an SQL UPDATE, INSERT, or (typically an SQL UPDATE, INSERT, or DELETE statement)DELETE statement)

use the use the StatementStatement class’s class’s executeUpdate()executeUpdate() method to invoke method to invoke the updatethe update

See the JDBC example

Page 29: Database Programming in Java Corresponds with Chapter 32, 33

Connecting to data source

Page 30: Database Programming in Java Corresponds with Chapter 32, 33

Connecting to data source

Load driver

Page 31: Database Programming in Java Corresponds with Chapter 32, 33

Connecting to data source

Identify Data source

(this is if you want to use ODBCAdministrator for DSN)

Page 32: Database Programming in Java Corresponds with Chapter 32, 33

Connecting to data source

Identify Data source

(Alternatively, for Access database you canspecify the location of the .mdb file)

Page 33: Database Programming in Java Corresponds with Chapter 32, 33

Connecting to data source

Connect to Data source

Page 34: Database Programming in Java Corresponds with Chapter 32, 33

Note: in this example, I am asking the user to enter an sql statement, then passing it to some methods I declared.

Page 35: Database Programming in Java Corresponds with Chapter 32, 33

Performing SQL query

Page 36: Database Programming in Java Corresponds with Chapter 32, 33

Performing SQL query

To perform a query or update, you need to first obtain a Statement object from the database connection.

Page 37: Database Programming in Java Corresponds with Chapter 32, 33

Performing SQL query

Get resultset from query

Page 38: Database Programming in Java Corresponds with Chapter 32, 33

Performing SQL query

If you want metadata (e.g. field names, field count, etc.), get the metadata object for the resultset

Page 39: Database Programming in Java Corresponds with Chapter 32, 33

Performing SQL query

Columncount and columnname are information about the metadata. getColumnCount gives the number of fields and getColumnName gives the name of a particular field.

Page 40: Database Programming in Java Corresponds with Chapter 32, 33

Performing SQL query

getString gives the value (in string format) of the data from a particular field of the result set.

The next() method of the ResultSet interface reads the next row…if it returns a null value this means that you are at the end of the resultset.

Page 41: Database Programming in Java Corresponds with Chapter 32, 33

Performing SQL update/delete/insert

The executeUpdate() method is used for an SQL update/delete/insert command. It returns an integer indicating how many rows were updated, added, or deleted.

Page 42: Database Programming in Java Corresponds with Chapter 32, 33

Using DatabaseMetaDataUsing DatabaseMetaData

Many methods that can be useful for Many methods that can be useful for obtaining:obtaining: Driver versionDriver version Database management systemDatabase management system Database URLDatabase URL List of all table, queries, etc.List of all table, queries, etc. Many more thingsMany more things

Page 43: Database Programming in Java Corresponds with Chapter 32, 33

This example shows how you can use DatabaseMetaData to get useful information about the database.