JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database...

42
JDBC JDBC

Transcript of JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database...

Page 1: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

JDBCJDBC

Page 2: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

PreliminariesPreliminaries

DatabaseDatabaseCollection of dataCollection of data

DBMSDBMSDatabase management systemDatabase management systemStores and organizes dataStores and organizes data

SQLSQLRelational databaseRelational databaseStructured Query LanguageStructured Query Language

Page 3: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Relational DatabaseRelational Database

Relational databaseRelational databaseTableTable

Rows, columnsRows, columnsPrimary keyPrimary key

Unique dataUnique data

SQL statementSQL statementQueryQuery

Page 4: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

SQLSQL

SQL overviewSQL overviewSQL keywordsSQL keywords

Page 5: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

SQL: SELECT QUERYSQL: SELECT QUERY

Simplest form of a SELECT querySimplest form of a SELECT querySELECTSELECT * * FROMFROM tableNametableName

SELECTSELECT * * FROMFROM authorsauthors

Select specific fields from a tableSelect specific fields from a tableSELECTSELECT authorIDauthorID, , lastNamelastName FROMFROM authorsauthors

Page 6: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

SQL: WHERE CLAUSESQL: WHERE CLAUSE

specify the selection criteriaspecify the selection criteriaSELECTSELECT columnName1columnName1, , columnName2columnName2, ,

… … FROMFROM tableNametableName WHEREWHERE criteriacriteriaSELECTSELECT title, editionNumber, copyright title, editionNumber, copyright

FROMFROM titles titles

WHEREWHERE copyright > 2000 copyright > 2000

WHEREWHERE clause condition operators clause condition operators<, >, <=, >=, =, <><, >, <=, >=, =, <>LIKELIKE

wildcard characterswildcard characters % % andand _ _

Page 7: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

SQL: ORDER BY ClauseSQL: ORDER BY Clause

Optional Optional ORDER BYORDER BY clause clause SELECTSELECT columnName1columnName1, , columnName2columnName2, … , … FROMFROM

tableNametableName ORDERORDER BYBY columncolumn ASCASC SELECTSELECT columnName1columnName1, , columnName2columnName2, … , … FROMFROM

tableNametableName ORDERORDER BYBY columncolumn DESCDESC ORDER BYORDER BY multiple fields multiple fields

ORDERORDER BYBY column1column1 sortingOrdersortingOrder, , column2column2 sortingOrdersortingOrder, …, …

Combine the Combine the WHEREWHERE and and ORDERORDER BYBY clauses clauses

Page 8: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

SQL: INSERTSQL: INSERT

Insert a row into a tableInsert a row into a tableINSERTINSERT INTOINTO tableNametableName ( ( columnName1columnName1, … , …

, , columnNameNcolumnNameN ) )

VALUESVALUES ( ( value1value1, … , , … , valueNvalueN ) )INSERTINSERT INTOINTO authors ( firstName, lastName authors ( firstName, lastName

))

VALUESVALUES ( ( ‘Sue’‘Sue’, , ‘Smith’‘Smith’ ) )

Page 9: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

SQL: UPDATESQL: UPDATE

Modify data in a tableModify data in a tableUPDATEUPDATE tableNametableName

SETSET columnName1columnName1 = = value1value1, … , , … , columnNameNcolumnNameN = = valueNvalueN

WHEREWHERE criteriacriteriaUPDATEUPDATE authors authors

SETSET lastName = ‘Jones’ lastName = ‘Jones’

WHEREWHERE lastName = lastName = ‘‘Smith’ Smith’ ANDAND firstName = firstName = ‘‘Sue’Sue’

Page 10: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

SQL: DELETESQL: DELETE

Remove data from a tableRemove data from a tableDELETE FROMDELETE FROM tableNametableName WHEREWHERE criteriacriteria

DELETE FROMDELETE FROM authors authors

WHEREWHERE lastName = ‘Jones’ lastName = ‘Jones’ ANDAND firstName = firstName = ‘‘Sue’Sue’

Page 11: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Layers of a DB ApplicationLayers of a DB Application

A database application consists of A database application consists of three layersthree layersDatabase Management System Database Management System Application logic (business rules) Application logic (business rules) Presentation logic (interface) Presentation logic (interface)

Page 12: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Java DB SupportJava DB Support

JDBCJDBCJava Data Base ConnectivityJava Data Base Connectivity

A set of interfaces to provide A set of interfaces to provide consistent API for accessing consistent API for accessing databases from different vendors databases from different vendors

Vendors must provide the Vendors must provide the implementation of these interfaces in implementation of these interfaces in order to facilitate a java application to order to facilitate a java application to access their databaseaccess their database

Page 13: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

JDBCJDBC

Implemented in java.sql packageImplemented in java.sql packageProvides set of interfaces to allow Provides set of interfaces to allow

access to third party databasesaccess to third party databasesPlatform independentPlatform independent

Changes underlying db doesn’t cause Changes underlying db doesn’t cause significant change in the application significant change in the application

Also allows access to vendor-specific Also allows access to vendor-specific featuresfeatures

Page 14: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

JDBC DriverJDBC Driver

JDBC Driver: JDBC Driver: set of classes that interface with a set of classes that interface with a

specific database engine. specific database engine. JDBC drivers exist for every major JDBC drivers exist for every major

database including: Oracle, SQL database including: Oracle, SQL Server, Sybase, and MySQL.Server, Sybase, and MySQL.

Page 15: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

JDBC DriverJDBC Driver

Java Application

JDBC Driver Manager

JDBC-ODBC Bridge

VendorSpecific

JDBC Driver

VendorSpecific

JDBC Driver

Database

Database

Page 16: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Database DriversDatabase Drivers Type 1 - Bridge DriversType 1 - Bridge Drivers

Drivers in Java code which connect a Java client to a Drivers in Java code which connect a Java client to a non-java database service (such as ODBC). non-java database service (such as ODBC).

Type 2 - Part-Java DriversType 2 - Part-Java Drivers ( (NativeNative)) Wraps (possibly existing) native code libraries with Java Wraps (possibly existing) native code libraries with Java

code to implement JDBC. code to implement JDBC. Type 3 - Network All-Java Drivers Type 3 - Network All-Java Drivers

(Middleware)(Middleware) All java code which connects to middleware to access a All java code which connects to middleware to access a

database via a network protocol. This type of driver may database via a network protocol. This type of driver may be used with applets or servlets. be used with applets or servlets.

Type 4 - Direct All-Java Drivers (Pure)Type 4 - Direct All-Java Drivers (Pure) This provides a pure Java JDBC implementation which This provides a pure Java JDBC implementation which

can be accessed directly and possibly provide services can be accessed directly and possibly provide services to networking middleware. to networking middleware.

Page 17: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

JDBC Drivers (Fig.)JDBC Drivers (Fig.)

JDBC

Type I“Bridge”

Type II“Native”

Type III“Middleware”

Type IV“Pure”

ODBCODBCDriver

CLI (.lib)

MiddlewareServer

Page 18: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

JDBC Application ArchitectureJDBC Application Architecture

Application JDBC Driver

Java code calls JDBC libraryJava code calls JDBC library JDBC loads a JDBC loads a driverdriver Driver talks to a particular databaseDriver talks to a particular databaseCan have more than one driver -> more than Can have more than one driver -> more than

one databaseone database Ideal: can change database engines without Ideal: can change database engines without

changing any application codechanging any application code

Page 19: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

JDBC InterfacesJDBC Interfaces

CallableStatement CallableStatement Connection Connection DatabaseMetaData DatabaseMetaData Driver Driver PreparedStatement PreparedStatement ResultSet ResultSet ResultSetMetaData ResultSetMetaData Statement Statement

Page 20: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

JDBC ClassesJDBC Classes

Date Date DriverManager DriverManager DriverPropertyInfo DriverPropertyInfo Time Time Timestamp Timestamp Types Types

Page 21: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

JDBCJDBC

Six step ProcedureSix step Procedure Load the JDBC DriverLoad the JDBC Driver Establish the Database ConnectionEstablish the Database Connection Create a Statement ObjectCreate a Statement Object Execute a QueryExecute a Query Process the ResultsProcess the Results Close the ConnectionClose the Connection

Page 22: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

JDBC CLASS USAGEJDBC CLASS USAGE

DriverManager

Driver

Connection

Statement

ResultSet

Page 23: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

JDBC: Loading the DriverJDBC: Loading the Driver

A simple reference to the driver A simple reference to the driver loads it into the JVMloads it into the JVMClass.forName(name_of_the_driver)Class.forName(name_of_the_driver)Driver name is a string representing the Driver name is a string representing the

complete hierarchy of the driver class complete hierarchy of the driver class i.e. the package and class namei.e. the package and class name

For a JDBC-ODBC DriverFor a JDBC-ODBC DriverClass.forName("sun.jdbc.odbc.JdbcOdbcDrivClass.forName("sun.jdbc.odbc.JdbcOdbcDriver");er");

Page 24: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Establish the ConnectionEstablish the Connection

Static method getConnection of Class Static method getConnection of Class Driver Manager returns a Connection Driver Manager returns a Connection object.object.

Can throw SQLException Can throw SQLException Connection con = Connection con =

DriverManager.getConnection(url, DriverManager.getConnection(url, user, password ) user, password )

Page 25: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Connection URLConnection URL

The only difficulty in establishing a The only difficulty in establishing a connection is specifying the correct URL.connection is specifying the correct URL.

General format of connection URL is General format of connection URL is jdbc:subprotocol:subnamejdbc:subprotocol:subname..JDBC indicates that this is a JDBC JDBC indicates that this is a JDBC

Connection.Connection.The subprotocol identifies the driver to be The subprotocol identifies the driver to be

usedusedThe subname identifies the database The subname identifies the database

name/location.name/location.

Page 26: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Connection URLConnection URL

For example, the following code uses For example, the following code uses a JDBC-ODBC bridge to connect to a JDBC-ODBC bridge to connect to the local database db:the local database db:String url = "jdbc:odbc:db";String url = "jdbc:odbc:db";

Connection con = Connection con = DriverManager.getConnection(url, DriverManager.getConnection(url, "cerami", "password");"cerami", "password");

Page 27: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Create a Statement ObjectCreate a Statement Object

The JDBC The JDBC StatementStatement object sends SQL object sends SQL statements to the database.statements to the database.

Statement objects are created from Statement objects are created from active active ConnectionConnection objects. objects.

For example:For example:Statement stat = con.createStatement();Statement stat = con.createStatement();

SQL calls can then be made on the SQL calls can then be made on the database through statement objectdatabase through statement object

Page 28: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Execute a QueryExecute a Query

executeQuery(String query)executeQuery(String query)Executes a select query on the database Executes a select query on the database

and returns the selected data in the and returns the selected data in the form of a ResultSet objectform of a ResultSet object

The returned ResultSet object may be The returned ResultSet object may be empty but cannot be nullempty but cannot be null

Throws SQLExceptionThrows SQLExceptionResultSet rs = stat.executeQuery ResultSet rs = stat.executeQuery

(“Select * from table”);(“Select * from table”);

Page 29: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Execute QueryExecute Query

executeUpdate(String query)executeUpdate(String query)Executes INSER, UPDATE, DELETE SQL Executes INSER, UPDATE, DELETE SQL

statementsstatementsReturns an integer value representing the Returns an integer value representing the

number of rows affected by this operationnumber of rows affected by this operationThrows SQLExceptionThrows SQLExceptionAlso supports DDL statements CREATE Also supports DDL statements CREATE

TABLE, DROP TABLE, ALTER TABLETABLE, DROP TABLE, ALTER TABLEint rows = executeUpdate(“delete * from int rows = executeUpdate(“delete * from

table”);table”);

Page 30: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Process the ResultProcess the Result

A A ResultSetResultSet contains the results of the SQL contains the results of the SQL queryquery

ResultSet MethodsResultSet MethodsAll methods can throw a All methods can throw a SQLExceptionSQLException

Close()Close()Releases the JDBC and database resourcesReleases the JDBC and database resourcesA ResultSet object is automatically closed when its A ResultSet object is automatically closed when its

associated statement object runs a new query.associated statement object runs a new query. getMetaData()getMetaData()

Returns ResultSetMetaData objectReturns ResultSetMetaData objectThis object contains information about the columns in This object contains information about the columns in

the ResultSet.the ResultSet.

Page 31: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

ResultSetResultSet

next()next()Attempts to move to the next row of Attempts to move to the next row of

data in the ResultSetdata in the ResultSetReturns true if successful andReturns true if successful andFalse otherwiseFalse otherwiseFirst call to the next() method positions First call to the next() method positions

the cursor at the first data rowthe cursor at the first data row

Page 32: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

ResultSetResultSet

findColumn(String)findColumn(String)Maps a ResultSet column name to a Maps a ResultSet column name to a

ResultSet column indexResultSet column indexReturns an integer value that Returns an integer value that

corresponds to the specified column corresponds to the specified column namename

Page 33: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

ResultSetResultSet

getXXX(String), getXXX(int)getXXX(String), getXXX(int)Returns the value from the column Returns the value from the column

specified by specified by column name (String version)column name (String version) or or column index (int) column index (int) as an as an XXXXXX Java type Java type

First column index is 1 not 0First column index is 1 not 0Returns 0 or Returns 0 or nullnull, if the value is a SQL , if the value is a SQL

NULLNULLCan call wasNull().Can call wasNull().Legal Legal getgetXxxXxx types typesdouble byte int

Date String floatshort long Time Object

Page 34: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Close the ConnectionClose the Connection

To close the database connectionTo close the database connectionstat.close();stat.close();con.close()con.close()

Page 35: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Mapping SQL Types To JAVAMapping SQL Types To JAVASQL type SQL type Java TypeJava TypeCHAR, CHAR, VARCHARVARCHAR, LONGVARCHAR, LONGVARCHAR StringStringNUMERICNUMERIC, DECIMAL, DECIMAL java.math.BigDecimaljava.math.BigDecimalBITBIT booleanbooleanTINYINTTINYINT bytebyteSMALLINTSMALLINT shortshortINTEGERINTEGER intintBIGINTBIGINT longlongREALREAL floatfloatFLOAT, FLOAT, DOUBLEDOUBLE doubledoubleBINARY, BINARY, VARBINARYVARBINARY, LONGVARBINARY, LONGVARBINARY byte[]byte[]DATEDATE java.sql.Datejava.sql.DateTIMETIME java.sql.Timejava.sql.TimeTIMESTAMPTIMESTAMP java.sql.Timestampjava.sql.Timestamp

Page 36: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Transaction ManagementTransaction Management

Transactions are Transactions are notnot explicitly explicitly opened and closedopened and closed

Instead, the connection has a state Instead, the connection has a state called called AutoCommitAutoCommit mode mode

if if AutoCommitAutoCommit is true, then every is true, then every statement is automatically statement is automatically committedcommitted

default case: truedefault case: true

Page 37: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Transaction ManagementTransaction Management

Connection.setAutoCommit(boolean)Connection.setAutoCommit(boolean) if if AutoCommitAutoCommit is false, then every is false, then every

statement is added to an ongoing statement is added to an ongoing transactiontransaction

you must explicitly commit or you must explicitly commit or rollback the transaction using rollback the transaction using Connection.commit() and Connection.commit() and Connection.rollback()Connection.rollback()

Page 38: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

JDBC Class DiagramJDBC Class Diagram

Page 39: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Stored ProceduresStored Procedures

Stored proceduresStored proceduresStore SQL statements in a databaseStore SQL statements in a databaseInvoke SQL statements by programs Invoke SQL statements by programs

accessing the databaseaccessing the database Interface Interface CallableStatementCallableStatement

Receive argumentsReceive argumentsOutput parametersOutput parameters

Page 40: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Meta DataMeta Data

Database/ConnectionDatabase/ConnectionDatabaseMetaData: getMetaData();DatabaseMetaData: getMetaData();

ResultSetResultSetResultSetMetaData: getMetaData()ResultSetMetaData: getMetaData()

Page 41: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Resultset MetadataResultset Metadata What's the number of columns in the ResultSet? What's the number of columns in the ResultSet? What's a column's name? What's a column's name? What's a column's SQL type? What's a column's SQL type? What's the column's normal max width in chars? What's the column's normal max width in chars? What's the suggested column title for use in printouts and displays? What's the suggested column title for use in printouts and displays? What's a column's number of decimal digits? What's a column's number of decimal digits? Does a column's case matter? Does a column's case matter? Will a write on the column definitely succeed? Will a write on the column definitely succeed? Can you put a NULL in this column? Can you put a NULL in this column? Is a column definitely not writable? Is a column definitely not writable? Can the column be used in a where clause? Can the column be used in a where clause? Is the column a signed number? Is the column a signed number? Is it possible for a write on the column to succeed? Is it possible for a write on the column to succeed? and so on...and so on...

Page 42: JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Database MetadataDatabase Metadata

What tables are available?What tables are available?What's our user name as known to What's our user name as known to

the database? the database? Is the database in read-only mode? Is the database in read-only mode?