Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

49
Overview Overview 1. What is JDBC? 1. What is JDBC? 2. 2. The JDBC-ODBC Bridge The JDBC-ODBC Bridge 3. 3. JDBC Pseudocode JDBC Pseudocode 4. 4. simpJDBC.java simpJDBC.java

Transcript of Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Page 1: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

OverviewOverview

1. What is JDBC?1. What is JDBC?

2.2. The JDBC-ODBC BridgeThe JDBC-ODBC Bridge

3.3. JDBC PseudocodeJDBC Pseudocode

4.4. simpJDBC.javasimpJDBC.java

Page 2: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

5.5. Meta DataMeta Data

6.6. Books.mdbBooks.mdb as an ODBC as an ODBC Data SourceData Source

Page 3: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

What is JDBC?What is JDBC?

JDBC provides a set of classes for Java JDBC provides a set of classes for Java with a standard SQL database access with a standard SQL database access interface. interface.

Allow programs to access to a wide Allow programs to access to a wide range of relational databases which range of relational databases which follow the ANSI SQL-2 standardfollow the ANSI SQL-2 standard

Provides an API for database "drivers" Provides an API for database "drivers" to make actual connections and to make actual connections and transactions to databases. transactions to databases.

Page 4: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

JDBC in UseJDBC in Use

Java program

connectivity

data processingutilities

JDBCdriver

for Oracle

driverFor MySQL

jdbc-odbcbridge

odbcdriver

Page 5: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

The JDBC-ODBC BridgeThe JDBC-ODBC Bridge

ODBC (Open Database Connectivity) is ODBC (Open Database Connectivity) is a Microsoft standard from the mid a Microsoft standard from the mid 1990’s.1990’s.

It is an API that allows C/C++ It is an API that allows C/C++ programs to execute SQL inside programs to execute SQL inside databasesdatabases

ODBC is supported by many products.ODBC is supported by many products.

Page 6: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

The JDBC-ODBC bridge allows Java The JDBC-ODBC bridge allows Java code to use the C/C++ interface of code to use the C/C++ interface of ODBCODBC– it means that JDBC can access many it means that JDBC can access many

different database productsdifferent database products

The layers of translation (Java --> C The layers of translation (Java --> C --> SQL) can slow down execution.--> SQL) can slow down execution.

Page 7: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

The JDBC-ODBC bridge comes The JDBC-ODBC bridge comes freefree with the JDK:with the JDK:– called called sun.jdbc.odbc.JdbcOdbcDriversun.jdbc.odbc.JdbcOdbcDriver

The ODBC driver for Microsoft The ODBC driver for Microsoft Access comes with MS OfficeAccess comes with MS Office– so it is easy to connect Java and so it is easy to connect Java and

AccessAccess

Page 8: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

JDBC DriversJDBC Drivers

list of drivers (freeware, list of drivers (freeware, shareware, and commercial) shareware, and commercial)

Sun Microsystems JDBC home Sun Microsystems JDBC home pagepage– Java.sun.com/products/jdbcJava.sun.com/products/jdbc

SQL materialsSQL materials– www.sql.orgwww.sql.org

Page 9: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

JDBC PseudoCodeJDBC PseudoCode

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

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

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

Continued

Page 10: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

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

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

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

Page 11: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Pseudocode DiagramPseudocode Diagram

DriveManager Connection Statement ResultSetcreates creates creates

Driver

SQL

SQL

data

data

make linkto driver

Page 12: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

DriveManagerDriveManager

It is responsible for establishing the It is responsible for establishing the connection to the database through connection to the database through the driver.the driver.

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

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

Page 13: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Name the Database Name the Database

The name and location of the The name and location of the database is given as a URLdatabase is given as a URL– the details of the URL vary the details of the URL vary

depending on the type of database depending on the type of database that is being usedthat is being used

Page 14: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

ODBC Database URLODBC Database URL

jdbc:odbc: //host.domain.com: 1511 jdbc:odbc: //host.domain.com: 1511 /data/file/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 15: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Statement ObjectStatement Object

The The StatementStatement object provides a object provides a ‘workspace’ where SQL queries can be ‘workspace’ where SQL queries can be created, executed, and results created, executed, and results collected.collected.

e.g.e.g.Statement st = Statement st = conn.createStatement():conn.createStatement():ResultSet rs = st.executeQuery(ResultSet rs = st.executeQuery(“ select * from Students” );“ select * from Students” );::st.close();st.close();

Page 16: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

ResultSet ObjectResultSet Object

Stores the results of a SQL Stores the results of a SQL query.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’ examined by moving a ‘pointer’ (cursor).(cursor).

Continued

Page 17: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

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

5

17

98

John

Mark

Paul

Peter

cursor

3

Page 18: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

DemoDemo

Set up Access Database Set up Access Database Set up ODBC sourceSet up ODBC source

Page 19: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Make a Access DatabaseMake a Access Database“JDBCStudent”“JDBCStudent”

Page 20: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Add Data to Students TableAdd Data to Students Table

Page 21: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Press “Add’ to 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”.

Add ODBC datasource

ControlPanel: administrator tools. ODBC Data Sources Administrator

Page 22: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Type in a source name, description, and press “Select” to browse to set the path to the JDBCStduent.mdb file.

Page 23: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Username & PasswordUsername & Password

The database’s link to the outside The database’s link to the outside (e.g. its ODBC interface) must be (e.g. its ODBC interface) must be configured to have a login and configured to have a login and passwordpassword

Page 24: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

ClicK AdvancedClicK Advanced Type in a username Type in a username

and password (guest).and password (guest).Click “Ok”Click “Ok”

Page 25: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

simpJDBC.javasimpJDBC.java// simpJDBC.java

import java.sql.*; public class JdbcSimple {

private java.sql.Connection connection;

public JdbcSimple(){

String url = "jdbc:odbc:cs483";

String username = "anonymous";

String password = "guest";

Page 26: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

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 27: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

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

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

+ rs.getString("firstName") );

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

:

Page 28: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

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 29: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Accessing a ResultSetAccessing a ResultSet

The The ResultSetResultSet class contains class contains many methods for accessing the many methods for accessing the value of a column of the current value of a column of the current rowrow– can use the column name or positioncan use the column name or position– e.g. get the value in the lastName e.g. get the value in the lastName

column:column:rs.getString("lastName")

Continued

Page 30: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

The ‘tricky’ aspect is that the The ‘tricky’ aspect is that the values are SQL data, and so must values are SQL data, and so must be converted to Java types/objects.be converted to Java 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 31: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Meta DataMeta Data Meta data is the information Meta data is the information aboutabout

the database:the database:– e.g. the number of columns, the types e.g. the number of columns, the types

of the columnsof the columns– meta data is the meta data is the schemaschema information information

ID Name Course Mark

007 James CS100 90

008 Jet Math100 80

meta data

Page 32: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Accessing Meta DataAccessing Meta Data

The The getMetaData()getMetaData() method can be method can be used on a used on a ResultSetResultSet object to object to create its meta data object.create its meta data object.

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

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

Page 33: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Using Meta DataUsing 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 34: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

More Meta Data More Meta Data MethodsMethods 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 returns true if column has signed numbersnumbers

isCurrency()isCurrency() etc.etc.

Page 35: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Summary: Setting up Summary: Setting up the Data Sourcethe Data Source Create a new DatabaseCreate a new Database

– AddressBookDBAddressBookDB ID, firstName, lastName, ... emailID, firstName, lastName, ... email

Create a DSN for the DatabaseCreate a DSN for the Database– DSN: Data Source NameDSN: Data Source Name

tells your program which database to use!tells your program which database to use! Done in the ODBC control panelDone in the ODBC control panel

the DSN is what will be required in the the DSN is what will be required in the URL to the Database for ODBC!!URL to the Database for ODBC!!

Page 36: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Summary: Steps in Summary: Steps in using JDBCusing JDBC Load the appropriate JDBC driverLoad the appropriate JDBC driver

– Done using dynamic class loading in JavaDone using dynamic class loading in Java Open a Connection to the DatabaseOpen a Connection to the Database Create a new query as an SQL StatementCreate a new query as an SQL Statement Execute the queryExecute the query Process the ResultSetProcess the ResultSet

– for database meta-data and the recordsfor database meta-data and the records Close the StatementClose the Statement Close the ResultSetClose the ResultSet Close the database connectionClose the database connection

Page 37: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Creating JDBC Creating JDBC statementsstatements A statement object is what sends your SQL A statement object is what sends your SQL

statement to DBMS. You create a statement statement to DBMS. You create a statement object and execute it. The method to use is object and execute it. The method to use is executeQuery or executeUpdate.executeQuery or executeUpdate.

– Statement stmt = Statement stmt = dbConnection.createStatement();dbConnection.createStatement();

– String sqlState = new String ( "SELECT String sqlState = new String ( "SELECT FirstName, LastName FROM ATable");FirstName, LastName FROM ATable");

– ResultSet myResults = ResultSet myResults = stmt.executeQuery( sqlState );stmt.executeQuery( sqlState );

Page 38: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

StatementStatement

Statement stmt = Statement stmt = connection.createStatement(); connection.createStatement();

stmt.executeQuery(String); stmt.executeQuery(String);

stmt.executeUpdate(String); stmt.executeUpdate(String);

Page 39: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

PreparedStatementPreparedStatement

Better performanceBetter performance

String sql = "select ? from atable";String sql = "select ? from atable";

PreparedStatement stmt =PreparedStatement stmt =

connection.prepareStatement(sql);connection.prepareStatement(sql);

stmt.setString(1, ”acolumn");stmt.setString(1, ”acolumn");

ResultSet rs = stmt.execute();ResultSet rs = stmt.execute();

The "1" replaces the first "?" in the statement The "1" replaces the first "?" in the statement

A "2" would replace the second "?" in the A "2" would replace the second "?" in the statementstatement

Page 40: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

ResultSetResultSet

Queries return results in a ResultSet Queries return results in a ResultSet Provides row-by-row access to results Provides row-by-row access to results Must call next() before getting dataMust call next() before getting data Can get data out by data type Can get data out by data type Can refer to columns by index or by Can refer to columns by index or by

name name

Page 41: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Getting and Getting and processing the resultsprocessing the results

while( myResults.next())while( myResults.next())

{{

System.out.println(myResults.getString(1) + System.out.println(myResults.getString(1) + " " + myResults.getString(2));" " + myResults.getString(2));

}}

Page 42: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Example: getTableExample: getTable

try { String query = "SELECT * FROM Authors";

statement = connection.createStatement(); resultSet = statement.executeQuery( query ); displayResultSet( resultSet ); statement.close(); } catch ( SQLException sqlex ) { sqlex.printStackTrace(); }

Page 43: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Display TableDisplay Table // position to first record boolean moreRecords = rs.next(); if ( ! moreRecords ) { return; } // get column heads ResultSetMetaData rsmd = rs.getMetaData(); for ( int i = 1; i <= rsmd.getColumnCount(); ++i ) columnHeads.addElement( rsmd.getColumnName( i ) ); // get row data do { rows.addElement( getNextRow( rs, rsmd ) ); } while ( rs.next() );

Page 44: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Get a rowGet a rowVector currentRow = new Vector(); for ( int i = 1; i <= rsmd.getColumnCount(); ++i ) switch( rsmd.getColumnType( i ) ) { case Types.VARCHAR: currentRow.addElement( rs.getString( i ) ); break; case Types.INTEGER: currentRow.addElement( new Long( rs.getLong( i ) ) ); break; default: System.out.println( "Type was: " + rsmd.getColumnTypeName( i ) ); }

Page 45: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

ResultSetMetaDataResultSetMetaData

ResultSetMetaData md = ResultSetMetaData md = rs.getMetaData(); rs.getMetaData();

md.getColumnName(int); md.getColumnName(int); md.getColumnType(int); md.getColumnType(int); md.getColumnCount();md.getColumnCount();

Page 46: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Find in a TableFind in a Table

Statement statement Statement statement =connection.createStatement();=connection.createStatement();

String query = "SELECT * FROM String query = "SELECT * FROM addresses " +addresses " +

"WHERE lastname = '" +"WHERE lastname = '" +

fields.last.getText() + "'";fields.last.getText() + "'";

ResultSet rs = ResultSet rs = statement.executeQuery( query );statement.executeQuery( query );

display( rs );display( rs );

Page 47: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Update a TableUpdate a TableStatement statement = connection.createStatement();

if ( ! fields.id.getText().equals( "" ) ) { String query = "UPDATE addresses SET " + "firstname='" + fields.first.getText() + "', lastname='" + fields.last.getText() + "' WHERE id=" + fields.id.getText(); int result = statement.executeUpdate( query ); if ( result == 1 ) output.append( "\nUpdate successful\n" ); else { output.append( "\nUpdate failed\n" ); }

Page 48: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Another Database Another Database Books.mdbBooks.mdb

Publishers

PublisherIDPublisherName

Titles

ISBNTitleEditionNumberYearPublishedDescriptionPublisherID

AuthorISBN

ISBNAuthorID

Authors

AuthorIDFirstNameLastNameYearBorn

1

8

88

1

1

Page 49: Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Building large Building large information systemsinformation systems ClientClient serverserver DatabaseDatabase