Database Programming in Java Corresponds with Chapter 32, 33

Preview:

Citation preview

Database Programming Database Programming in Javain 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).

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)

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

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

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)

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)

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.

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.

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.

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.

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.

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

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.

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.

ApplicationApplication

Driver ManagerDriver Manager

DriverDriver

DataDataSourceSource(MS Access)(MS Access)

DriverDriver

DataDataSourceSource(Oracle)(Oracle)

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.

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.

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

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.

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

JDBC ClassesJDBC Classes

DateDate DriverManagerDriverManager DriverProperyInfoDriverProperyInfo TimeTime TimeStampTimeStamp TypesTypes

DriverManager will be used in the example and assignment

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

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

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

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

Connecting to data source

Connecting to data source

Load driver

Connecting to data source

Identify Data source

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

Connecting to data source

Identify Data source

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

Connecting to data source

Connect to Data source

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

Performing SQL query

Performing SQL query

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

Performing SQL query

Get resultset from query

Performing SQL query

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

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.

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.

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.

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

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

Recommended