lecture 05: database programming (jdbc)

25
1 Lecture 05: Database Programming (JDBC)

Upload: braith

Post on 21-Jan-2016

50 views

Category:

Documents


0 download

DESCRIPTION

Lecture 05: Database Programming (JDBC). Outline. JDBC overview JDBC API Reading: Chapter 10.5 Pointbase Developer Manual. Embedded SQL. Direct SQL (= ad-hoc SQL) is rarely used In practice: SQL is embedded in some application code user interaction, devices, programming logic - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Lecture 05: Database Programming (JDBC)

1

Lecture 05: Database Programming (JDBC)

Page 2: Lecture 05: Database Programming (JDBC)

2

Outline

• JDBC overview

• JDBC API

Reading:Chapter 10.5 Pointbase Developer Manual

Page 3: Lecture 05: Database Programming (JDBC)

3

Embedded SQL

• Direct SQL (= ad-hoc SQL) is rarely used

• In practice: SQL is embedded in some application code– user interaction, devices, programming logic

• SQL code is enbedded using special syntax into a host language

Page 4: Lecture 05: Database Programming (JDBC)

4

JDBC (Java DB Connectivity)

Java application{ ..."SELECT ... FROM ... WHERE"... }

DBMS

Page 5: Lecture 05: Database Programming (JDBC)

5

JDBC Drivers

Javaapplication

JDBC-Driver manager

NativeProtocol driver

JDBC-Net-driver

NativeAPI-driver

JDBC-ODBCbridge

Client libraryDB-

MiddlewareODBC

Client library

JDBC-API

Page 6: Lecture 05: Database Programming (JDBC)

6

Running a JDBC Application

Phase Task Relevant java.sql classes

Initialisation

Processing

Termination

Load driverCreate connection

Generate SQL statementsProcess result data

Terminate connectionRelease data structures

DriverManagerConnection

StatementResultSet etc.

ConnectionStatement etc.

Page 7: Lecture 05: Database Programming (JDBC)

7

A Simple JDBC applicationloadDriver

getConnection

createStatement

execute(SQL)

Result handling

Last execution ?

closeStatment

closeConnection

no

yes

InitialContext ic = new InitialContext();

DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/aberer"; );

out.println("db found");

connection = ds.getConnection();

out.println("connection established");

Statement stmt = con.Statement („SELECT * FROM data WHERE date = '01-01-04' “);

ResultSet rset = stmt.executeQuery();

while (rset.next()) {...}

stmt.close();

con.close();

Page 8: Lecture 05: Database Programming (JDBC)

8

Loading of Driver

• Creates an instance of the driver

• Registers driver in the driver manager• Explicit loading

String l_driver = "com.pointbase.jdbc.jdbcUniversalDriver";Class.forName(l_driver).newInstance();

• Several drivers can be loaded and registered

Page 9: Lecture 05: Database Programming (JDBC)

9

Addressing Database

• A connection is a session with one database

• Databases are addressed using a URL of the form "jdbc:<subprotocol>:<subname>"

• Examples"jdbc:pointbase:embedded:sample""jdbc:pointbase:server://<server ip address>/sample"

Page 10: Lecture 05: Database Programming (JDBC)

10

Connecting to Database

• Connection is establishedconn = DriverManager.getConnection(URL,USERID,PWD);

• Connection is closedcon.close();

Page 11: Lecture 05: Database Programming (JDBC)

11

Implicit Driver Loading

• Create DataSource objectjdbcDataSource ds = new jdbcDataSource();ds.setDatabaseName(l_URL);ds.setUser(l_UID);ds.setPassword(l_PWD);ds.setCreateDatabase(true);

• Establish connection with the database and return a Connection objectconn = ds.getConnection();

Page 12: Lecture 05: Database Programming (JDBC)

12

Simple SQL Statements

• Statement object for invocationstmt = conn.createStatement();ResultSet rset= stmt.executeQuery( "SELECT address,script,type FROM worklist");

• ResultSet object for result processing

Page 13: Lecture 05: Database Programming (JDBC)

13

Impedance Mismatch

• Example: SQL in Java:– Java uses int, char[..], objects, etc– SQL uses tables

• Impedance mismatch = incompatible types

• Why not use only one language?– SQL cannot do everything that the host language

can do

• Solution: use cursors

Page 14: Lecture 05: Database Programming (JDBC)

14

Using Cursors

• Access to tuples– ResultSet object manages a cursor for tuple access– ExampleStatement stmt=con.createStatement();

ResultSet rset=stmt.executeQuery (“SELECT …”);while (rset.next()) { …}

rset.close();

c1 c2 c3 c4

Page 15: Lecture 05: Database Programming (JDBC)

15

Accessing Attributes (Columns)

• Access to columns of a tuple– Using column index or column name– Example

while (rset.next()) {String address = rset.getString(1);String type = rset.getString(“type”);String script = rset.getString( rset.findColumn(“script”)); ...

}

c1 c2 c3 c4

Page 16: Lecture 05: Database Programming (JDBC)

16

More on Cursors

• Cursors can also modify a relationrset.updateString("script", "ebay");

• The cursor can be a scrolling one: can go forward, backwardfirst(), last(), next(), previous()

• We can determine the order in which the cursor will get tuples by the ORDER BY clause in the SQL query

Page 17: Lecture 05: Database Programming (JDBC)

17

Dynamic JDBC Statements

• Variables within SQL statement

• Precompiled once, multiple executions• PreparedStatement for invocation

PreparedStatement stmt = con.prepareStatement ( "SELECT * FROM data WHERE date = ?");

stmt.setDate ('01-01-04', j_date);

ResultSet rset = stmt.executeQuery();

Page 18: Lecture 05: Database Programming (JDBC)

18

SQL Data Types

• For passing parameters to prepared statements specific SQL data types are needed

• Examplejava.util.Date jd = new java.util.Date();java.sql.Date j_date = new java.sql.Date(jd.getTime());

Page 19: Lecture 05: Database Programming (JDBC)

19

Update Statements

• Updates have no result setint result = stmt.executeUpdate("delete from worklist");

• Return value of executeUpdate – DDL-statement: always 0– DML-statement: number of tuples

Page 20: Lecture 05: Database Programming (JDBC)

20

Error Handling

• Each SQL statement can generate errors– Thus each SQL method should be put into a

try-block

• Exceptions are reported through exceptions of class SQLException

Page 21: Lecture 05: Database Programming (JDBC)

21

Example

Import java.sql.*;public class JdbcDemo {public static void main(String[] args) {

try {Class. forName(com.pointbase.jdbc.jdbcUniversalDriver);

} catch (ClassNotFoundException exc) {System.out.println(exc.getMessage());}

try {Connection con = DriverManager.getConnection(“jdbc:jdbc:demo",”tux”,”penguin”);Statement stmt = con.createStatement();ResultSet rs = stmt.executeQuery(“SELECT * FROM data”);while (rs.next()) {… process result tuples …}} catch (SQLException exc) {System.out.println(“SQLException: “ + exc.getMessage());} } }

Page 22: Lecture 05: Database Programming (JDBC)

22

Metadata

• Metadata allows to develop schema independent applications for databases– Generic output methods– Type dependent applications

• Two types of metadata are accessible– on result sets– on the database

Page 23: Lecture 05: Database Programming (JDBC)

23

ResultSet Metadata

• java.sql.ResultSetMetaData describes the structure of a result set object

• Information about a ResultSet object– Names, types and access properties of columns

Page 24: Lecture 05: Database Programming (JDBC)

24

Database Metadata

• java.sql.DatabaseMetaData provides information about the database (schema etc.)

• Information about the database – Name of database– Version of database– List of all tables– List of supported SQL types– Support of transactions

Page 25: Lecture 05: Database Programming (JDBC)

25

Example

ResultSet rset = stmt.executeQuery(“SELECT * FROM data”);

ResultSetMetaData rsmeta = rset.getMetaData();

int numCols = rsmeta.getColumnCount();

for (int i=1; i<=numCols; i++) { int ct = rsmeta.getColumnType(i); String cn = rsmeta.getColumnName(i); String ctn = rsmeta.getColumnTypeName(i); System.out.println(“Column #” + i + “: “ + cn + “ of type “ + ctn + “ (JDBC type: “ + ct + “)”);}