V22.0470 OOP: JDBC V22.0470 Week 8 V22.0470 Week 8 Objective Objective – to give some background on JDBC to give some background on JDBC to help with the lab exercises to help with the lab exercises Fall, 2002 Introduction to Java Database Connectivity (JDBC)
81
Embed
V22.0470 OOP: JDBC1 V22.0470 Week 8 v Objective –to give some background on JDBC to help with the lab exercises Fall, 2002 Introduction to Java Database.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
V22.0470 OOP: JDBC 1
V22.0470 Week 8V22.0470 Week 8
ObjectiveObjective– to give some background on JDBC to help to give some background on JDBC to help
with the lab exercises with the lab exercises
Fall, 2002
Introduction to Java Database Connectivity
(JDBC)
V22.0470 OOP: JDBC 2
OverviewOverview
1. 1. What is JDBC?What is JDBC?
2. 2. The JDBC-ODBC BridgeThe JDBC-ODBC Bridge
3.3. Four Kinds of JDBC DriversFour Kinds of JDBC Drivers
4.4. JDBC PseudocodeJDBC Pseudocode
5.5. simpJDBC.javasimpJDBC.java
Continued
V22.0470 OOP: JDBC 3
6.6. Meta DataMeta Data
7.7. Books.mdbBooks.mdb as an ODBC as an ODBC Data SourceData Source
8.8. Table in Table in Books.mdbBooks.mdb
9.9. More InformationMore Information
V22.0470 OOP: JDBC 4
1. What is JDBC?1. What is JDBC?
JDBC is an interface which allows Java JDBC is an interface which allows Java code to execute SQL statements inside code to execute SQL statements inside relational databasesrelational databases– the databases must follow the ANSI SQL-2 the databases must follow the ANSI SQL-2
standardstandard
V22.0470 OOP: JDBC 5
JDBC in UseJDBC in Use
Java program
connectivity
data processingutilities
JDBCdriver
for Oracle
driverfor Sybase
jdbc-odbcbridge
odbcdriver
V22.0470 OOP: JDBC 6
2. The JDBC-ODBC Bridge2. The JDBC-ODBC Bridge
ODBC (Open Database Connectivity) is a ODBC (Open Database Connectivity) is a Microsoft standard from the mid 1990’s.Microsoft standard from the mid 1990’s.
It is an API that allows C/C++ programs to It is an API that allows C/C++ programs to execute SQL inside databasesexecute SQL inside databases
ODBC is supported by many products.ODBC is supported by many products.
Continued
V22.0470 OOP: JDBC 7
The JDBC-ODBC bridge allows Java code The JDBC-ODBC bridge allows Java code to use the C/C++ interface of ODBCto use the C/C++ interface of ODBC– it means that JDBC can access many different it means that JDBC can access many different
database productsdatabase products
The layers of translation (Java --> C --> The layers of translation (Java --> C --> SQL) can slow down execution.SQL) can slow down execution.
Continued
V22.0470 OOP: JDBC 8
The JDBC-ODBC bridge comes The JDBC-ODBC bridge comes freefree with with the JDK:the JDK:– called called sun.jdbc.odbc.JdbcOdbcDriversun.jdbc.odbc.JdbcOdbcDriver
The ODBC driver for Microsoft Access The ODBC driver for Microsoft Access comes with MS Officecomes with MS Office– so it is easy to connect Java and Accessso it is easy to connect Java and Access
V22.0470 OOP: JDBC 9
3. Four Kinds of JDBC Driver3. Four Kinds of JDBC Driver
1. JDBC-ODBC Bridge1. JDBC-ODBC Bridge– translate Java to the ODBC APItranslate Java to the ODBC API
2. Native API2. Native API– translate Java to the database’s own APItranslate Java to the database’s own API
Continued
V22.0470 OOP: JDBC 10
3. Native Protocol3. Native Protocol– use Java to access the database more directly use Java to access the database more directly
using its low level protocolsusing its low level protocols
4. Net Protocol4. Net Protocol– use Java to access the database via networking use Java to access the database via networking
middleware (usually TCP/IP)middleware (usually TCP/IP)– required for networked applicationsrequired for networked applications
V22.0470 OOP: JDBC 11
JDBC DriversJDBC Drivers
A searchable list of drivers (freeware, A searchable list of drivers (freeware, shareware, and commercial) can be found shareware, and commercial) can be found at:at:
It is responsible for establishing the It is responsible for establishing the connection to the database through the connection to the database through the driver.driver.
The name and location of the database is The name and location of the database is given as a URLgiven as a URL– the details of the URL vary depending on the the details of the URL vary depending on the
type of database that is being usedtype of database that is being used
The The StatementStatement object provides a ‘workspace’ object provides a ‘workspace’ where SQL queries can be created, executed, where SQL queries can be created, executed, and results collected.and results collected.
“ select * from Authors” );“ select * from Authors” );::
st.close();st.close();
V22.0470 OOP: JDBC 19
4.5. ResultSet Object4.5. ResultSet Object
Stores the results of a SQL query.Stores the results of a SQL query.
A A ResultSetResultSet object is similar to a object is similar to a ‘table’ of answers, which can be ‘table’ of answers, which can be examined by moving a ‘pointer’ (cursor).examined by moving a ‘pointer’ (cursor).
The database’s link to the outside (e.g. its The database’s link to the outside (e.g. its ODBC interface) must be configured to ODBC interface) must be configured to have a login and passwordhave a login and password– details for ODBC are given laterdetails for ODBC are given later
V22.0470 OOP: JDBC 27
5.2. Accessing a ResultSet5.2. Accessing a ResultSet
The The ResultSetResultSet class contains many class contains many methods for accessing the value of a methods for accessing the value of a column of the current rowcolumn of the current row– can use the column name or positioncan use the column name or position– e.g. get the value in the lastName column:e.g. get the value in the lastName column:
rs.getString("lastName")
Continued
V22.0470 OOP: JDBC 28
The ‘tricky’ aspect is that the values are The ‘tricky’ aspect is that the values are SQL data, and so must be converted to Java SQL data, and so must be converted to Java types/objects.types/objects.
There are many methods for There are many methods for accessing/converting the data, e.g.accessing/converting the data, e.g.– getString(), getDate(), getInt(), getString(), getDate(), getInt(), getFloat(), getObject()getFloat(), getObject()
V22.0470 OOP: JDBC 29
6. Meta Data6. Meta Data
Meta data is the information Meta data is the information aboutabout the the database:database:– e.g. the number of columns, the types of the e.g. the number of columns, the types of the
columnscolumns– meta data is the meta data is the schemaschema information information
ID Name Course Mark
007 James Bond Shooting 99
008 Aj. Andrew Kung Fu 1
meta data
V22.0470 OOP: JDBC 30
6.1. Accessing Meta Data6.1. Accessing Meta Data
The The getMetaData()getMetaData() method can be used method can be used on a on a ResultSetResultSet object to create its meta object to create its meta data object.data object.
– number of decimal digits in the columnnumber of decimal digits in the column isSigned()isSigned()
– returns true if column has signed numbersreturns true if column has signed numbers isCurrency()isCurrency() etc.etc.
V22.0470 OOP: JDBC 33
7. Books.mdb as an ODBC Data Source7. Books.mdb as an ODBC Data Source
1. Click on1. Click on“32 bit ODBC”“32 bit ODBC”in the Controlin the ControlPanel.Panel.This displays the This displays the ODBC Data ODBC Data Sources Sources AdministratorAdministrator
V22.0470 OOP: JDBC 34
2. Press “Add’ to 2. Press “Add’ to add a data source add a data source and select and select Microsoft Access Microsoft Access Driver (*.mdb). Driver (*.mdb). Press “Finish”.Press “Finish”.
V22.0470 OOP: JDBC 35
3. Type in a 3. Type in a source name, source name, description, description, and press “Select” and press “Select” to browse to set to browse to set the path to the the path to the Books.mdb file.Books.mdb file.
Now click onNow click on“Advanced”.“Advanced”.
V22.0470 OOP: JDBC 36
4. Type in a username 4. Type in a username and password (guest).and password (guest).Click “Ok”Click “Ok”
They can be defined into two types:They can be defined into two types:– those using the those using the Data Definition LanguageData Definition Language
– those using the those using the Data Manipulation LanguageData Manipulation Language (DML)(DML)
selectselect others, including insert, update, deleteothers, including insert, update, delete
V22.0470 OOP: JDBC 43
1.1. create Example1.1. create Example
create table studInfo (create table studInfo ( studID int not null primary key, studID int not null primary key, lastname char(25) not null, lastname char(25) not null, firstname char(40) not null, firstname char(40) not null, address char(25), address char(25),
Unspecified rows will be filled with SQL Unspecified rows will be filled with SQL nullnull values. values.
The The studIDstudID, , lastnamelastname, and , and firstnamefirstname must be supplied.must be supplied.
V22.0470 OOP: JDBC 45
1.3. update and delete Examples1.3. update and delete Examples
update studInfo set lastname = ‘Bland’update studInfo set lastname = ‘Bland’where studID = 7where studID = 7
delete from studInfo where studID = 7delete from studInfo where studID = 7
V22.0470 OOP: JDBC 46
2. Executing DDL and DML2. Executing DDL and DML
From last time: From last time: selectselect statements are statements are executed from JDBC with executed from JDBC with executeQuery()executeQuery()..
The method returns a table of results The method returns a table of results (a resultSet object).(a resultSet object).
e.g.e.g.ResultSet rs = statement.executeQuery(
"SELECT lastName, firstName
FROM Authors" );
continued
V22.0470 OOP: JDBC 47
But most SQL statements do not return a But most SQL statements do not return a tabletable– DDL statements, e.g. create, dropDDL statements, e.g. create, drop– most DML statements, e.g. insert, updatemost DML statements, e.g. insert, update
If you try to execute these kinds of If you try to execute these kinds of statements with statements with executeQuery()executeQuery(), an , an SQLExceptionSQLException will occur. will occur.
V22.0470 OOP: JDBC 48
2.1. executeUpdate()2.1. executeUpdate()
Used to execute SQL statements that Used to execute SQL statements that change the database, table, or rowchange the database, table, or row– e.g. DDL: create, drope.g. DDL: create, drop– e.g. DML: insert, update, deletee.g. DML: insert, update, delete
V22.0470 OOP: JDBC 49
2.2. BuildTables.java2.2. BuildTables.java
This program uses create and insert to build This program uses create and insert to build a new table, called urlInfo, inside a new table, called urlInfo, inside Books.mdb.Books.mdb.
V22.0470 OOP: JDBC 50
CodeCode// BuildTables.java// Create a new table, urlInfo, inside Books.mdb// The table has three columns: id, name, url
import java.sql.*;
public class simpJDBC {
public static void main(String[] args) { // The URL for the Books database.
// ’Protected' by a login and password. String url = "jdbc:odbc:Books"; String username = "anonymous"; String password = "guest";
:
V22.0470 OOP: JDBC 51
// SQL table creation and insertion// SQL table creation and insertion String[] SQLStats = { String[] SQLStats = {
"create table urlInfo (id int,Name char(48), "create table urlInfo (id int,Name char(48), url char(80))",url char(80))", "insert into urlInfo values(1, 'Andrew D', "insert into urlInfo values(1, 'Andrew D', 'http://fivedots.coe.psu.ac.th/~ad')", 'http://fivedots.coe.psu.ac.th/~ad')", "insert into urlInfo values(2, "insert into urlInfo values(2, 'JavaSoft Home Page', 'JavaSoft Home Page', 'http://www.javasoft.com')",'http://www.javasoft.com')", "insert into urlInfo values(3, 'PSU', "insert into urlInfo values(3, 'PSU', 'http://www.psu.ac.th')” };'http://www.psu.ac.th')” };
try { // load the JDBC-ODBC Bridge driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // connect to db using DriverManager Connection conn =
The 4 SQL commands are executed inside The 4 SQL commands are executed inside the single statement object.the single statement object.
executeUpdate()executeUpdate() returns an integer returns an integer– the number of rows affectedthe number of rows affected– not used in not used in BuildTables.javaBuildTables.java
SQL commands inside a SQL commands inside a PreparedStatementPreparedStatement object are object are compiledcompiled– they will execute faster than SQL in a they will execute faster than SQL in a StatementStatement object object
– but the compilation takes timebut the compilation takes time
PreparedStatementsPreparedStatements are often used for SQL are often used for SQL commands that will be executed repeatedly.commands that will be executed repeatedly.
V22.0470 OOP: JDBC 57
3.1. PlaceHolders3.1. PlaceHolders
SQL commands in a SQL commands in a PreparedStatementPreparedStatement can can contain contain placeholdersplaceholders– these can be changed at run time to vary the these can be changed at run time to vary the
meaning of the commandmeaning of the command
Placeholders are represented by ‘?’ in the Placeholders are represented by ‘?’ in the SQL command. SQL command.
The ‘?’s must be replaced by real values The ‘?’s must be replaced by real values before the statement is executed.before the statement is executed.
continued
V22.0470 OOP: JDBC 59
The ‘?’s can be replaced using a wide range The ‘?’s can be replaced using a wide range of “set” methods for different types.of “set” methods for different types.e.g.e.g.– setString()setString(), , setInt()setInt(), , setFloat()setFloat(), , setDate()setDate(), ..., ...
V22.0470 OOP: JDBC 60
3.2. PlaceHolders.java3.2. PlaceHolders.java
Update the Update the URLInfoURLInfo table table– replace “Andrew D by “Andrew Davison”replace “Andrew D by “Andrew Davison”
Use a Use a PreparedStatementPreparedStatement object with two object with two placeholdersplaceholders– this simple example could be coded using this simple example could be coded using StatementStatement objects objects
V22.0470 OOP: JDBC 61
CodeCode
// PlaceHolders.javaimport java.sql.*;
public class PlaceHolders {
public static void main(String[] args) { // The URL for the Books database.
// It is 'protected' by a login and password. String url = "jdbc:odbc:Books"; String username = "anonymous"; String password = "guest";
:
V22.0470 OOP: JDBC 62
try { // load the JDBC-ODBC Bridge driver
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
// connect to db using DriverManager Connection conn =
// Fill in the '?'s ps.setString(1, "Andrew Davison"); ps.setInt(2, 1); // his id is '1'
// make the change int noRowsUpdated = ps.executeUpdate(); System.out.println("No. of Rows updated:
" + noRowsUpdated);
:
V22.0470 OOP: JDBC 64
// Close down conn.close(); } catch ( ClassNotFoundException cnfex ) { System.err.println(
"Failed to load JDBC/ODBC driver." ); cnfex.printStackTrace(); System.exit( 1 ); // terminate program } catch ( SQLException sqlex ) { System.err.println( sqlex ); sqlex.printStackTrace(); } } // end of main()
} // end of PlaceHolders class
V22.0470 OOP: JDBC 65
Execution ResultsExecution Results
c> java PlaceHoldersc> java PlaceHoldersNo. of Rows updated: 1No. of Rows updated: 1
C>C>
changed
V22.0470 OOP: JDBC 66
4. Database Metadata4. Database Metadata
Metadata for the database is information Metadata for the database is information about all the tables, and all the columns in about all the tables, and all the columns in each table (i.e. their each table (i.e. their schemaschema).).
Once the metadata object has been created, Once the metadata object has been created, details about the tables and the columns can details about the tables and the columns can be extracted with:be extracted with:– getTables()getTables()– getColumns()getColumns()
Both methods return Both methods return resultSetsresultSets (tables) of (tables) of information.information.
The arguments are used to limit the The arguments are used to limit the information which is returnedinformation which is returned– if an argument is not to be used, if an argument is not to be used,
then set it to nullthen set it to null
V22.0470 OOP: JDBC 69
Argument DetailsArgument Details
String catalogString catalog
– this specifies the catalog to search for tablesthis specifies the catalog to search for tables String schemePatternString schemePattern
– select tables which use the pattern in a schema select tables which use the pattern in a schema namename
– a schema pattern is a string. Two special chars:a schema pattern is a string. Two special chars: % means ‘any substring’% means ‘any substring’ _ means ‘any character’_ means ‘any character’
continued
V22.0470 OOP: JDBC 70
– e.g. “%data” will match schema names: e.g. “%data” will match schema names: “data”, “Mydata”, “Yourdata”“data”, “Mydata”, “Yourdata”
– e.g. “data_” will match schema names:e.g. “data_” will match schema names: “datas”, “data1” “datas”, “data1”
String tablePatternString tablePattern
– used to select tables based on their namesused to select tables based on their names– may use “%” and “_”may use “%” and “_”
continued
V22.0470 OOP: JDBC 71
String[] typesString[] types
– select tables based on their typesselect tables based on their types– possible types:possible types:
getColumns() ResultSet FormatgetColumns() ResultSet Format
The resultSet (e.g The resultSet (e.g crscrs) has 18 columns! ) has 18 columns! Some of the useful ones:Some of the useful ones:– COLUMN_NAMECOLUMN_NAME– DATA_TYPE: DATA_TYPE:
type of the data in the columntype of the data in the column– COLUMN_SIZECOLUMN_SIZE
num. of chars or the numerical precision in the num. of chars or the numerical precision in the columncolumn