v22.0470 week 8

81
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)

Upload: kaleb

Post on 05-Jan-2016

22 views

Category:

Documents


0 download

DESCRIPTION

V22.0470 Week 8. Fall, 2002. Objective to give some background on JDBC to help with the lab exercises. Introduction to Java Database Connectivity (JDBC). Overview. 1. What is JDBC? 2. The JDBC-ODBC Bridge 3.Four Kinds of JDBC Drivers 4.JDBC Pseudocode 5. simpJDBC.java. Continued. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: V22.0470 Week 8

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)

Page 2: V22.0470 Week 8

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

Page 3: V22.0470 Week 8

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

Page 4: V22.0470 Week 8

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

Page 5: V22.0470 Week 8

V22.0470 OOP: JDBC 5

JDBC in UseJDBC in Use

Java program

connectivity

data processingutilities

JDBCdriver

for Oracle

driverfor Sybase

jdbc-odbcbridge

odbcdriver

Page 6: V22.0470 Week 8

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

Page 7: V22.0470 Week 8

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

Page 8: V22.0470 Week 8

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

Page 9: V22.0470 Week 8

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

Page 10: V22.0470 Week 8

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

Page 11: V22.0470 Week 8

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:

http://www.javasoft.com/products/http://www.javasoft.com/products/

jdbc/driversjdbc/drivers

Page 12: V22.0470 Week 8

V22.0470 OOP: JDBC 12

4. JDBC PseudoCode4. JDBC PseudoCode

All JDBC programs do the following:All JDBC programs do the following:– 1) load the JDBC driver1) load the JDBC driver

– 2) Specify the name and location of the 2) Specify the name and location of the database being useddatabase being used

– 3) Connect to the database with a 3) Connect to the database with a ConnectionConnection objectobject

Continued

Page 13: V22.0470 Week 8

V22.0470 OOP: JDBC 13

– 4) Execute a SQL query using a 4) Execute a SQL query using a StatementStatement objectobject

– 5) Get the results in a 5) Get the results in a ResultSetResultSet object object

– 6) Finish by closing the 6) Finish by closing the ResultSetResultSet, , StatementStatement and and ConnectionConnection objects objects

Page 14: V22.0470 Week 8

V22.0470 OOP: JDBC 14

4.1. Pseudocode as a Diagram4.1. Pseudocode as a Diagram

DriveManager Connection Statement ResultSetcreates creates creates

Driver

SQL

SQL

data

data

make linkto driver

Page 15: V22.0470 Week 8

V22.0470 OOP: JDBC 15

4.2. DriveManager4.2. DriveManager

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.

e.g.e.g.Class.forName(

"sun.jdbc.odbc.JdbcOdbcDriver");Connection conn = DriveManager.getConnection(url);

Page 16: V22.0470 Week 8

V22.0470 OOP: JDBC 16

4.3. Name the Database 4.3. Name the Database

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

Page 17: V22.0470 Week 8

V22.0470 OOP: JDBC 17

ODBC Database URLODBC Database URL

jdbc:odbc: //host.domain.com: 2048 /data/filejdbc:odbc: //host.domain.com: 2048 /data/file

The commsprotocol

The machineholding the database.

The portused for the connection.

The path tothe databaseon the machine

e.g. jdbc:odbc:Books

Page 18: V22.0470 Week 8

V22.0470 OOP: JDBC 18

4.4. Statement Object4.4. Statement Object

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.

e.g.e.g.Statement st = Statement st =

conn.createStatement():conn.createStatement():ResultSet rs = st.executeQuery(ResultSet rs = st.executeQuery(

“ select * from Authors” );“ select * from Authors” );::

st.close();st.close();

Page 19: V22.0470 Week 8

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).

Continued

Page 20: V22.0470 Week 8

V22.0470 OOP: JDBC 20

Cursor operations:Cursor operations:– first()first(),, last() last(), , next()next(), , previous()previous(), etc., etc.

Typical code:Typical code:while( rs.next() ) {while( rs.next() ) { // process the row; // process the row;}}

23

5

17

98

John

Mark

Paul

Peter

cursor

Page 21: V22.0470 Week 8

V22.0470 OOP: JDBC 21

5. simpJDBC.java5. simpJDBC.java// simpJDBC.java// Displays the firstnames and lastnames// of the Authors table in the Books db.

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";

:

Page 22: V22.0470 Week 8

V22.0470 OOP: JDBC 22

try { // load the JDBC-ODBC Bridge driver

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// connect to db using DriverManager Connection conn =

DriverManager.getConnection( url, username, password );

// Create a statement object Statement statement = conn.createStatement();

// Execute the SQL query

ResultSet rs = statement.executeQuery( "SELECT lastName, firstName FROM Authors" );

:

Page 23: V22.0470 Week 8

V22.0470 OOP: JDBC 23

// Print the result set while( rs.next() )

System.out.println( rs.getString("lastName") + ", "

+ rs.getString("firstName") );

// Close down statement.close(); conn.close(); }

:

Page 24: V22.0470 Week 8

V22.0470 OOP: JDBC 24

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 simpJDBC class

Page 25: V22.0470 Week 8

V22.0470 OOP: JDBC 25

OutputOutput

Page 26: V22.0470 Week 8

V22.0470 OOP: JDBC 26

5.1. Username & Password5.1. Username & Password

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

Page 27: V22.0470 Week 8

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

Page 28: V22.0470 Week 8

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()

Page 29: V22.0470 Week 8

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

Page 30: V22.0470 Week 8

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.

e.g.e.g.ResultSetMetaData md = ResultSetMetaData md =

rs.getMetaData();rs.getMetaData();

Page 31: V22.0470 Week 8

V22.0470 OOP: JDBC 31

6.2. Using Meta Data6.2. Using Meta Data

int numCols = int numCols = md.md.getColumnCount();getColumnCount();

for (int i = 0; i <= numCols; i++) {for (int i = 0; i <= numCols; i++) { if (md.getColumnType(i) == if (md.getColumnType(i) ==

Types.CHAR)Types.CHAR) System.out.println( System.out.println(

md.getColumnName(i) )md.getColumnName(i) )}}

Page 32: V22.0470 Week 8

V22.0470 OOP: JDBC 32

6.3. More Meta Data Methods6.3. More Meta Data Methods

getTableName()getTableName() getPrecision()getPrecision()

– 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.

Page 33: V22.0470 Week 8

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

Page 34: V22.0470 Week 8

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”.

Page 35: V22.0470 Week 8

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”.

Page 36: V22.0470 Week 8

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”

Page 37: V22.0470 Week 8

V22.0470 OOP: JDBC 37

8. Table in Books.mdb8. Table in Books.mdb

Publishers

PublisherIDPublisherName

Titles

ISBNTitleEditionNumberYearPublishedDescriptionPublisherID

AuthorISBN

ISBNAuthorID

Authors

AuthorIDFirstNameLastNameYearBorn

1

8

88

1

1

Page 38: V22.0470 Week 8

V22.0470 OOP: JDBC 38

9. More Information9. More Information

Java: How to ProgramJava: How to ProgramDeitel and Deitel, 3rd Ed.Deitel and Deitel, 3rd Ed.Chapter 18.Chapter 18.

Beginning Java 2Beginning Java 2Ivor HortonIvor HortonChapters 18 and 19Chapters 18 and 19

Continued

Page 39: V22.0470 Week 8

V22.0470 OOP: JDBC 39

Current Information:Current Information:http://www.javasoft.com/products/jdbchttp://www.javasoft.com/products/jdbc

The JDK Documentation and tutorialThe JDK Documentation and tutorial– the JDBC ‘trail’ is very goodthe JDBC ‘trail’ is very good

Page 40: V22.0470 Week 8

V22.0470 OOP: JDBC 40

Java Database Connectivity (JDBC) 2

Page 41: V22.0470 Week 8

V22.0470 OOP: JDBC 41

OverviewOverview

1. 1. SQL StatementsSQL Statements

2. 2. Executing DDL and DMLExecuting DDL and DML

3.3. PreparedStatement ObjectsPreparedStatement Objects

4.4. Database MetadataDatabase Metadata

5.5. More InformationMore Information

Page 42: V22.0470 Week 8

V22.0470 OOP: JDBC 42

1. SQL Statements1. SQL Statements

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

(DDL)(DDL) create, delete tablescreate, delete tables

– those using the those using the Data Manipulation LanguageData Manipulation Language (DML)(DML)

selectselect others, including insert, update, deleteothers, including insert, update, delete

Page 43: V22.0470 Week 8

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),

:: email char(25) email char(25)););

Page 44: V22.0470 Week 8

V22.0470 OOP: JDBC 44

1.2. insert Example1.2. insert Example

insert into studInfo insert into studInfo (studID, lastname, firstname, email) (studID, lastname, firstname, email) values (7, ‘Bond’, ‘James’, values (7, ‘Bond’, ‘James’,

[email protected]’)‘[email protected]’)

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.

Page 45: V22.0470 Week 8

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

Page 46: V22.0470 Week 8

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

Page 47: V22.0470 Week 8

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.

Page 48: V22.0470 Week 8

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

Page 49: V22.0470 Week 8

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.

Page 50: V22.0470 Week 8

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";

:

Page 51: V22.0470 Week 8

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 =

DriverManager.getConnection( url, username, password );:

Page 52: V22.0470 Week 8

V22.0470 OOP: JDBC 52

// Create a statement object Statement statement =

conn.createStatement();

// Create urlInfo table for (int i = 0; i < SQLStats.length; i++) {

statement.executeUpdate(SQLStats[i]); System.out.println("Processed: " +

SQLStats[i]); }

// Close down statement.close(); conn.close();}

:

Page 53: V22.0470 Week 8

V22.0470 OOP: JDBC 53

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 BuildTables class

Page 54: V22.0470 Week 8

V22.0470 OOP: JDBC 54

NotesNotes

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

Page 55: V22.0470 Week 8

V22.0470 OOP: JDBC 55

3. PreparedStatement Objects3. PreparedStatement Objects

PreparedStatementPreparedStatement objects are created in a objects are created in a similar way to similar way to StatementStatement objects objects

e.g.e.g.PreparedStatement ps =PreparedStatement ps =

conn.prepareStatement(conn.prepareStatement(“ SQL query...”);“ SQL query...”);

continued

Page 56: V22.0470 Week 8

V22.0470 OOP: JDBC 56

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.

Page 57: V22.0470 Week 8

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.

continued

Page 58: V22.0470 Week 8

V22.0470 OOP: JDBC 58

Example:Example:String newName = “update authors String newName = “update authors

set lastName = ? set lastName = ? where AuthorID = ? ”;where AuthorID = ? ”;

PreparedStatement ps = PreparedStatement ps =

conn.prepareStatement(newName);conn.prepareStatement(newName);

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

Page 59: V22.0470 Week 8

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(), ..., ...

Page 60: V22.0470 Week 8

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

Page 61: V22.0470 Week 8

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";

:

Page 62: V22.0470 Week 8

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 =

DriverManager.getConnection( url, username,

password );

:

Page 63: V22.0470 Week 8

V22.0470 OOP: JDBC 63

// Create PreparedStatement String changeAD =

"update urlInfo set name = ? where id = ?";

PreparedStatement ps = conn.prepareStatement(changeAD);

// 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);

:

Page 64: V22.0470 Week 8

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

Page 65: V22.0470 Week 8

V22.0470 OOP: JDBC 65

Execution ResultsExecution Results

c> java PlaceHoldersc> java PlaceHoldersNo. of Rows updated: 1No. of Rows updated: 1

C>C>

changed

Page 66: V22.0470 Week 8

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).).

Code Fragment:Code Fragment:Connection conn = Connection conn = DriverManager.getConnection( url, DriverManager.getConnection( url,

username, username, password ); DatabaseMetaData metadata = password ); DatabaseMetaData metadata =

conn.getMetaData()conn.getMetaData();;

continued

Page 67: V22.0470 Week 8

V22.0470 OOP: JDBC 67

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.

Page 68: V22.0470 Week 8

V22.0470 OOP: JDBC 68

4.1. getTables()4.1. getTables()

ResultSet trs =ResultSet trs =metadata.getTables( String catalog,metadata.getTables( String catalog,

String schemePattern, String schemePattern, String tableNamePattern, String tableNamePattern, String[] types);String[] types);

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

Page 69: V22.0470 Week 8

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

Page 70: V22.0470 Week 8

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

Page 71: V22.0470 Week 8

V22.0470 OOP: JDBC 71

String[] typesString[] types

– select tables based on their typesselect tables based on their types– possible types:possible types:

““TABLE”TABLE”,, “SYSTEM TABLE” “SYSTEM TABLE”, , “VIEW”“VIEW”

Page 72: V22.0470 Week 8

V22.0470 OOP: JDBC 72

Code FragmentCode Fragment

Get the metadata for all the normal tables:Get the metadata for all the normal tables:

String[] tableTypes = { “TABLE” };String[] tableTypes = { “TABLE” };ResultSet trs = metadata.getTables(ResultSet trs = metadata.getTables(null, null,null, null,null, tableTypes);null, tableTypes);

Page 73: V22.0470 Week 8

V22.0470 OOP: JDBC 73

getTables() ResultSet FormatgetTables() ResultSet Format

The resultSet (e.g The resultSet (e.g trstrs) has five columns:) has five columns:– TABLE_CATTABLE_CAT::

a String specifying the catalog (or null)a String specifying the catalog (or null)– TABLE_SCHEMTABLE_SCHEM

a String specifying the table schema (or null)a String specifying the table schema (or null)– TABLE_NAMETABLE_NAME (the table name) (the table name)– TABLE_TYPETABLE_TYPE (its type) (its type)– REMARKSREMARKS

a String describing the tablea String describing the table

Page 74: V22.0470 Week 8

V22.0470 OOP: JDBC 74

4.2. viewTables.java4.2. viewTables.java// Pull metadata from Books.mdb// Print the name of every table in Books.mdb// Uses getTables()

import java.sql.*;

public class viewTables {

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”;

:

Page 75: V22.0470 Week 8

V22.0470 OOP: JDBC 75

try { // load the JDBC-ODBC Bridge driver

Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );

// connect to db using DriverManager Connection conn =

DriverManager.getConnection( url, username, password );

// Get the database metadata DatabaseMetaData metadata =

conn.getMetaData();:

Page 76: V22.0470 Week 8

V22.0470 OOP: JDBC 76

// Extract the table-based metadata String [] tableTypes = { "TABLE" };

ResultSet tables = metadata.getTables(null,

null, null, tableTypes );

// Print the table names String tableName; while( tables.next() ) { tableName =

tables.getString("TABLE_NAME"); System.out.println( tableName );

}:

Page 77: V22.0470 Week 8

V22.0470 OOP: JDBC 77

// 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 viewTables class

Page 78: V22.0470 Week 8

V22.0470 OOP: JDBC 78

UsageUsage

Page 79: V22.0470 Week 8

V22.0470 OOP: JDBC 79

4.3. getColumns()4.3. getColumns()

ResultSet crs =ResultSet crs =metadata.getColumns( String catalog,metadata.getColumns( String catalog,

String schemePattern, String schemePattern, String tableNamePattern, String tableNamePattern, String columnPattern);String columnPattern);

The first 3 arguments are as in The first 3 arguments are as in getTables()getTables()

columnPatterncolumnPattern selects a column based on the selects a column based on the pattern matching its name.pattern matching its name.

Page 80: V22.0470 Week 8

V22.0470 OOP: JDBC 80

Code FragmentCode Fragment

Get the metadata for all the columns in the “Get the metadata for all the columns in the “URLInfoURLInfo” table:” table:

ResultSet crs = metadata.getColumns(ResultSet crs = metadata.getColumns(null, null,null, null,“URLInfo”, null);“URLInfo”, null);

Page 81: V22.0470 Week 8

V22.0470 OOP: JDBC 81

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