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

Post on 24-Dec-2015

282 views 0 download

Tags:

Transcript of 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

5.5. Meta DataMeta Data

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

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.

JDBC in UseJDBC in Use

Java program

connectivity

data processingutilities

JDBCdriver

for Oracle

driverFor MySQL

jdbc-odbcbridge

odbcdriver

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.

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.

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

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

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

– 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

Pseudocode DiagramPseudocode Diagram

DriveManager Connection Statement ResultSetcreates creates creates

Driver

SQL

SQL

data

data

make linkto driver

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

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

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

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

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

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

DemoDemo

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

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

Add Data to Students TableAdd Data to Students Table

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

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

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

ClicK AdvancedClicK Advanced Type in a username Type in a username

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

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

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

:

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

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

+ rs.getString("firstName") );

// Close down statement.close(); 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 simpJDBC class

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

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

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

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

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

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.

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!!

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

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

StatementStatement

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

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

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

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

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

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

}}

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

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

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

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

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

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

Another Database Another Database Books.mdbBooks.mdb

Publishers

PublisherIDPublisherName

Titles

ISBNTitleEditionNumberYearPublishedDescriptionPublisherID

AuthorISBN

ISBNAuthorID

Authors

AuthorIDFirstNameLastNameYearBorn

1

8

88

1

1

Building large Building large information systemsinformation systems ClientClient serverserver DatabaseDatabase