JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database...
-
Upload
winfred-ronald-burke -
Category
Documents
-
view
242 -
download
4
Transcript of JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database...
JDBCJDBC
PreliminariesPreliminaries
DatabaseDatabaseCollection of dataCollection of data
DBMSDBMSDatabase management systemDatabase management systemStores and organizes dataStores and organizes data
SQLSQLRelational databaseRelational databaseStructured Query LanguageStructured Query Language
Relational DatabaseRelational Database
Relational databaseRelational databaseTableTable
Rows, columnsRows, columnsPrimary keyPrimary key
Unique dataUnique data
SQL statementSQL statementQueryQuery
SQLSQL
SQL overviewSQL overviewSQL keywordsSQL keywords
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
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 _ _
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
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’ ) )
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’
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’
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)
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
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
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.
JDBC DriverJDBC Driver
Java Application
JDBC Driver Manager
JDBC-ODBC Bridge
VendorSpecific
JDBC Driver
VendorSpecific
JDBC Driver
Database
Database
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.
JDBC Drivers (Fig.)JDBC Drivers (Fig.)
JDBC
Type I“Bridge”
Type II“Native”
Type III“Middleware”
Type IV“Pure”
ODBCODBCDriver
CLI (.lib)
MiddlewareServer
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
JDBC InterfacesJDBC Interfaces
CallableStatement CallableStatement Connection Connection DatabaseMetaData DatabaseMetaData Driver Driver PreparedStatement PreparedStatement ResultSet ResultSet ResultSetMetaData ResultSetMetaData Statement Statement
JDBC ClassesJDBC Classes
Date Date DriverManager DriverManager DriverPropertyInfo DriverPropertyInfo Time Time Timestamp Timestamp Types Types
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
JDBC CLASS USAGEJDBC CLASS USAGE
DriverManager
Driver
Connection
Statement
ResultSet
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");
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 )
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.
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");
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
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”);
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”);
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.
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
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
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
Close the ConnectionClose the Connection
To close the database connectionTo close the database connectionstat.close();stat.close();con.close()con.close()
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
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
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()
JDBC Class DiagramJDBC Class Diagram
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
Meta DataMeta Data
Database/ConnectionDatabase/ConnectionDatabaseMetaData: getMetaData();DatabaseMetaData: getMetaData();
ResultSetResultSetResultSetMetaData: getMetaData()ResultSetMetaData: getMetaData()
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...
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?