Top Banner
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale [email protected] Room - Faner 3131 1
34

Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

Jan 06, 2018

Download

Documents

Noel Goodwin

JDBC – Java DataBase Connectivity – Industry standard interface for connecting to relational databases from Java – Independent of any DBMS – Allows three things Establish a connection with Relational databases Send SQL statements Process the results – Provides two APIs API for application writers API for driver writers Introduction to JDBC 3
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

Access Databases from Java Programs via JDBC

Tessema M. Mengistu Department of Computer Science

Southern Illinois University [email protected]

Room - Faner 3131

1

Page 2: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

Outline – Introduction to JDBC– Connect to a database using Java Database

Connectivity (JDBC) – Create and execute a query using JDBC– Process and manipulate the result of a query– Disconnect from the database– Overview of SQLJ

2

Page 3: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

• JDBC – Java DataBase Connectivity– Industry standard interface for connecting to

relational databases from Java– Independent of any DBMS– Allows three things

• Establish a connection with Relational databases• Send SQL statements• Process the results

– Provides two APIs• API for application writers• API for driver writers

Introduction to JDBC

3

Page 4: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

JDBC Architecture

Application JDBC Driver

• Java code calls JDBC library• JDBC loads a driver • Driver talks to a particular database• Can have more than one driver -> more than one

database• Ideal: can change database engines without

changing any application code4

Page 5: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

• Is an interpreter that translates JDBC method calls to vendor-specific database commands

• Implements interfaces in java.sql • Can also provide a vendor’s extensions to the JDBC standard

DriverJDBC calls

Database commands

Database

A JDBC Driver

5

Page 6: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

JDBC Drivers

• Type I: “Bridge”• Type II: “Native”• Type III: “Middleware”• Type IV: “Pure”

6

Page 7: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

JDBC Drivers

JDBC

Type I“Bridge”

Type II“Native”

Type III“Middleware”

Type IV“Pure”

ODBC ODBCDriver

CLI (.lib)

MiddlewareServer

7

Page 8: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

Overview of Querying a Database With JDBC

Query

Close

ProcessResults

Connect

8

Page 9: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

Query

Close

Connect

Processresults

Register the driver

Connect to the database

Stage 1: Connect

9

Page 10: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

Registering a Driver

• Statically load driver Class.forName(“Driver Name”);

• Use the jdbc.drivers system property• Every driver has its own name

– For example• mysql - com.mysql.jdbc.Driver• Oracle - oracle.jdbc.driver.OracleDriver

10

Page 11: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

Connection to the Database

• Handled by DriverManager Object• Calls getConnection() Method

• Accepts– JDBC URL,– username – password

• Returns a Connection object

• Throws java.sql.SQLException

11

Page 12: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

JDBC URLs• JDBC uses a URL to identify the database connection

jdbc:subprotocol:source• Each driver has its own subprotocol• Each subprotocol has its own syntax for the source

12

Page 13: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

Connection• A Connection represents a session with a specific

database.• Within the context of a Connection, SQL statements are

executed and results are returned.• Can have multiple connections to a database• Also provides “metadata” -- information about the

database, tables, and fields• Also methods to deal with transactions

13

Page 14: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

Obtaining a Connection

String url = jdbc:oracle:thin:@dbserv.cs.siu.edu:1521:cs"; try {

Class.forName ("oracle.jdbc.driver.OracleDriver");Connection con = DriverManager.getConnection(url);

}catch (ClassNotFoundException e)

{ e.printStackTrace(); }catch (SQLException e)

{ e.printStackTrace(); }

14

Page 15: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

Close

Connect

Query Create a statement

Processresults

Query the database

Stage 2: Query

15

Page 16: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

Statement

• A Statement object is used for executing a SQL statement and obtaining the results produced by it.

• Different types of Statements – Statement – PreparedStatement – CallabaleStatment

16

Page 17: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

Statement

• Statement– Used for executing a static SQL statement– Created by createStatement()method

on the connection object – Returns a new Statement object

17

Page 18: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

PreparedStatment • Creates precompiled SQL statements - more efficient than

Statement class• Can also allow specifying parameters that can be filled during

run time • Usually used if the statements is going to execute more than

once • Created by prepareStatement()method on the

connection object – Accepts the query – returns a new PreparedStatement object

18

Page 19: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

CallableStatment• Many DBMS can store individual or set of SQL

statements in a database– Stored Procedures

• JDBC allows programs to invoke stored procedures using CallableStatment interface

• A Callable statement object holds parameters for calling stored procedures

• Created by prepareCall(String sql)– Accepts the query – returns a new CallableStatement object

19

Page 20: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

Statement Methods• executeQuery(String)

– Accepts SQL query– Execute a SQL query that returns a single ResultSet

• executeUpdate(String) – Execute a SQL INSERT, UPDATE or DELETE statement.

Returns the number of rows changed.• Execute()

– Execute a SQL statement that may return multiple results.

20

Page 21: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

Close

QueryStep through the results

Processresults

Assign results to Java variables

Connect

Stage 3: Process the Results

21

Page 22: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

ResultSet• A ResultSet provides access to a table of data

generated by executing a Statement. • Only one ResultSet per Statement can be open at

once.• The table rows are retrieved in sequence.• A ResultSet maintains a cursor pointing to its

current row of data. • The 'next' method moves the cursor to the next

row.

22

Page 23: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

ResultSet Methods

• boolean next() – activates the next row– the first call to next() activates the first row– returns false if there are no more rows

23

Page 24: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

ResultSet Methods

• Type getType(int columnIndex)– returns the given field as the given type– fields indexed starting at 1 (not 0)

• Type getType(String columnName)– same, but uses name of field– less efficient

• int findColumn(String columnName)– looks up column index given column name

24

Page 25: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

ResultSet Methods

• String getString(String columnName) • boolean getBoolean(String columnName) • byte getByte(String columnName) • short getShort(String columnName) • int getInt(String columnName) • long getLong(String columnName) • float getFloat(String columnName) • double getDouble(String columnName)• Date getDate(String columnName) • Time getTime(String columnName) • Timestamp getTimestamp(String columnName)

25

Page 26: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

Connect

Query

Processresults

Close

Close the result set

Close the statement

Close the connection

Stage 4: Close

26

Page 27: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

Close• Close the ResultSet object

• void close() – disposes of the ResultSet– allows you to re-use the Statement that created it– automatically called by most Statement methods

• Close the Statement Object • void close()

• Close the connection• void close()

27

Page 28: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

• Step 1: import java.sql Package • Step2: Load and register the driver• Step 3:Connect to the database• Step 4: Create statements• Step 5: Execute statements & Process the

Result• Step 6: close ResultSet and Statement• Step 7: Close the connection

28

Page 29: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

JDBC Object Classes

• DriverManager– Loads, chooses drivers

• Driver– connects to actual database

• Connection– a series of SQL statements to and from the DB

• Statement– a single SQL statement

• ResultSet– the records returned from a Statement

29

Page 30: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

Mapping Java Types to SQL Types

SQL type Java TypeCHAR, VARCHAR, LONGVARCHAR StringNUMERIC, DECIMAL java.math.BigDecimalBIT booleanTINYINT byteSMALLINT shortINTEGER intBIGINT longREAL floatFLOAT, DOUBLE doubleBINARY, VARBINARY, LONGVARBINARY byte[]DATE java.sql.DateTIME java.sql.TimeTIMESTAMP java.sql.Timestamp

30

Page 31: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

SQLJ• SQLJ is a set of programming extensions that

allow a programmer using the Java programming language to embed statements that provide SQL database requests

• Specifications for embedding SQL statements in Java programs

• Alternative to JDBC• Syntax

– #sql { ….}

31

Page 32: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

SQLJ• //SQLJ int n; #sql {INSERT INTO emp VALUES(:n)};• //JDBC

int n; String query = “INSERT INTO emp VALUES(?)”Statement stmt= con.prepareStatment (query)

stmt.setInt(1,n);stmt.execute();stmt.close();

32

Page 33: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

SQLJ

33

Page 34: Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale

34