UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

27
UFCE4Y-20-3 1 UFCE4Y-20-3 Components and Services Julia Dawson

Transcript of UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

Page 1: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 1

UFCE4Y-20-3Components and

Services

Julia Dawson

Page 2: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 2

JDBC

Java Database Connectivity

Page 3: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 3

What is JDBC

Java Database Connectivity (JDBC) is an API for the Java programming language that defines how a client may access a database.

It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases.

The Java Platform, Standard Edition includes the JDBC API together with an ODBC implementation of the API enabling connections to any relational database that supports ODBC.

This driver is native code and not Java.

http://en.wikipedia.org/wiki/JDBC

Page 4: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 4

Middleware Middleware is computer software that connects

software components or applications. It is used most often to support complex, distributed

applications. It includes web servers, application servers, content

management systems, and similar tools that support application development and delivery.

Middleware is especially integral to modern information technology based on XML, SOAP, Web services, and service-oriented architecture.

http://en.wikipedia.org/wiki/Middleware

Page 5: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 5

RDBMS

Relational Database Management System

Database is under the control of a DBAApplication logic is isolated from dataMany views from same dataComputing power distributed

> 90% of VB applications are DB access

Page 6: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 6

Client Server Model

RDBMS

SQL

Oracle

Files

Code

Cobol

Code RDBMS

SQL

VB & Oracle

GUI

HTML

RDBMS

SQL

Browser, Java & Oracle

Code

GUI

Page 7: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 7

DB AccessObjectives Database Vendor Independent

Not bound to a supplier

Database Technology Independent Use X/Open SQL Call Level Interface

Medium Level Interface Without support for full SQL/Java mapping

Hardware Platform Independent Compiled code can run on other platforms

Page 8: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 8

JDBC Structure

Java Application

JDBC Manager

JDBC Bridge

Database

Vendor Tech. Java & Native Java - Protocol Java – Net

http://java.sun.com/products/jdbc/driverdesc.html

Page 9: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 9

JDBC 1.0 Classes (1)

java.sql.* DriverManager

The basic service for managing a set of JDBC drivers. When the method getConnection is called, the DriverManager will attempt to locate a suitable driver

Connection A connection (session) with a specific database. SQL

statements are executed and results are returned within the context of a connection.

Page 10: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 10

JDBC 1.0 Classes (2)

java.sql.* Statement

The object used for executing a static SQL statement and returning the results it produces.

ResultSet A table of data representing a database result set,

which is usually generated by executing a statement that queries the database.

A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row.

Page 11: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 11

Summary

JDBC is a simple way to access a DBJDBC programs are portableJDBC programs are not vendor specificThe GUI can be separated from the DB

codeComponent use encourages separate

location for the DB server, application code and the GUI

Page 12: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 12

Building a DB

Saved as student.mdb

Page 13: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 13

Add ODBC

Page 14: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 14

import java.sql.*;public class DBStudent {

public static void main(String[ ] args) { Connection con; Statement st; ResultSet rs; String query = "select * from students"; try { // Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:class", "", ""); st = con.createStatement(); rs = st.executeQuery(query); while (rs.next()) { System.out.println(rs.getString(2) + ":" + s.getString(3)); } rs.close(); st.close(); con.close(); } catch (Exception e) { System.err.println("Trouble at mill ..." +e); } } //main } //class

Example

Page 15: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 15

Example Code (1)import java.sql.*;

public class DBStudent {

public static void main(String[] args) { Connection con; Statement st; ResultSet rs; String query = "select * from students"; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:class", "", ""); st = con.createStatement(); rs = st.executeQuery(query);

Run Query and get pointer/cursor to results

Make Connection to ODBC database called class

Add Driver to Driver List

Locate SQL classes

Page 16: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 16

Example Code (2)

while (rs.next( ) ) { System.out.println( rs.getString(2) +" : "+ rs.getString(3) ) ; } rs.close( ); st.close( ); con.close( ); } catch ( Exception e ) { System.err.println("Trouble at mill ..." + e ); }

} //main } //class

Iterate (move cursor) over ResultSet

Releases object's database and JDBC resources immediately

Get column contents

Jane:BrownJo:BloggsSophie:Smith

OUTPUT

Page 17: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 17

Connecting ....

The driver must be registered with the JDBC DriverManager Load the driver class using :Class.forName()

try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Class.forName("com.oracle.jdbc.OracleDriver");}catch (ClassNotFoundException e) { /* Do exception stuff .. */}

Can load database drivers dynamically!

Page 18: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 18

JDBC URLs

The JDBC Driver use a JDBC URL to identify and connect to particular database. Eg:

jdbc.odbc.studbjdbc.oracle.thin:@ivor:1526:csm1jdbc.hsql:c/temp/appleDBjdbc.hsql.http://www.....

Each driver is able to recognises it's own URLs

Page 19: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 19

Making the Connection Connection con = DriverManager.getConnection( "url", "user", "password");

User and password may be blank for some databases

Registered drivers are quizzed to see if they recognise the url

Url, user and password can be obtained from (for example):• a properties file • a Servlet init() method • an HTML form

Always explicitly close the connection after use - otherwise others processes may be blocked from connecting.

Page 20: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 20

SQL Statements (3 types)

StatementA basic SQL statement

PreparedStatementA precompiled SQL statement - can improve

efficiency (eg. repeat INSERT)CallableStatement

To access procedures within the stored database (eg. PL/SQL)

Page 21: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 21

Statement Get a statement object for the connection thus:Statement stmt = con.createStatement();

Now perform an SQL statement and get the result like this:ResultSet rs = stmt.executeQuery("select * from names");

If a statement should return no result (eg. UPDATE or DELETE)Get the number of rows affected (for example):int count = stmt.executeUpdate("update from names where ....");

See also execute()

NOTE: These calls will close any other ResultSet associated with this Statement.

Page 22: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 22

Processing ResultSet Statement st = con.createStatement();ResultSet rs = st.executeQuery( "select id, name, phone from company");

while (rs.next()) { System.out.print("Id is " + rs.getString("ID") + ", Name is " + rs.getString("Name") + ", Phone is " + rs.getString("PHONE");} //while

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

NOTE: Column name is case insensitiveCould also get columns by position (starting at 1). System.out.print("Id is " + rs.getString(1)

Page 23: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 23

SQL Data types <mapping> Java types SQL type Java Type getXXX()

CHAR, VARCHAR ... String getString()NUMERIC, DECIMAL java.Math.BigDecimal getBigDecimal()BIT boolean getBoolean()INTEGER int getInt()FLOAT, DOUBLE double getDouble()BINARY byte [ ] getBytes()DATE java.sql.Date getDate()TIME java.sql.Time getTime()

NOTE: Not all drivers honour these.The getString() method returns a String representation of most of types.

Page 24: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 24

Beware of Nulls (Empty fields)

If a column has null (empty) values - unpredictable results can occur.

Best to trap these - first getXXX() the value and then test for null using wasNull()

int amount = rs.getInt("STOCK");if (rs.wasNull()) { System.out.print("Null");} else { System.out.print(amount);}

Page 25: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 25

ResultSetMetaDataGives information about the structure of a particular ResultSet:

number of columns rsmd.getColumnCount()names of these columns rsmd.getColumnName(i)kind of data in each column rsmd.getColumnTypeName(i)

ResultSet rs = st.executeQuery("SELECT ....ResultSetMetaData rsmd = rs.getMetaData();

int columnCount = rsmd.getColumnCount();for (int i=1; i<= rsmd.getColumnCount(); i++) { System.out.print(rsmd.getColumnLabel(col) ...... See Also: DatabaseMetaData

Page 26: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 26

Escape Sequences … make special characters literal.

Wildcards

st.executeQuery( "SELECT * from NAMES where id like 'SM\_%' {escape '\'}“);

The "_" character is normally a wildcard for single character.

Special CharactersFor example escaping the single quote inside a string.

Page 27: UFCE4Y-20-31 UFCE4Y-20-3 Components and Services Julia Dawson.

UFCE4Y-20-3 27

Where to go from here …

Oracle JDBC tutorial

See Links on the module home page

Next CAS practical will use material from here …