37
1 JDBC – Java Database Connectivity CS 236369, Spring 2010

1 JDBC – Java Database Connectivity CS 236369, Spring 2010

Embed Size (px)

DESCRIPTION

3 JDBC (Java Database Connectiveity) is an API (Application Programming Interface)  That is, a collection of classes and interfaces JDBC is used for accessing databases from Java applications Information is transferred from relations to objects and vice-versa

Citation preview

Page 1: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

1

JDBC – Java Database Connectivity

CS 236369, Spring 2010

Page 2: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

2

Today’s Menu

JDBC Architecture Using JDBC Timeout ResultSet Object Null Values Prepared Statements

Page 3: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

3

JDBC (Java Database Connectiveity) is an API (Application Programming Interface) That is, a collection of classes and interfaces

JDBC is used for accessing databases from Java applications

Information is transferred from relations to objects and vice-versa

Page 4: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

4

JDBC Architecture

Page 5: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

5

JDBC Architecture

Java code calls JDBC library JDBC loads a driver The driver talks to a particular DBMS An application can work with several DBMS by using

corresponding drivers

Page 6: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

6

“Movies” Relation

movieName producer releaseDate

Movie1 Producer1 1.1.2000

Movie2 Producer2 1.1.2001

Movie3 Producer3 3.4.2003

Page 7: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

7

7 Steps for Using JDBC

1. Load the driver2. Define the connection URL3. Establish the connection4. Create a Statement object5. Execute a query using the Statement6. Process the result7. Close the connection

Page 8: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010
Page 9: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

9

1. Loading the Driver

Class.forName(“com.mysql.jdbc.Driver ”); Class.forName loads the given class dynamically When the driver is loaded, it automatically

creates an instance of itself registers this instance within DriverManager

Another way:Driver driver = new com.mysql.jdbc.Driver();DriverManager.registerDriver(driver);

MySql JDBC driver can be downloaded from here.

Page 10: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010
Page 11: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

11

2. Define the connection URL

Every database is identified by a URL Given a URL, DriverManager looks for the driver that

can talk to the corresponding database DriverManager tries all registered drivers,until a suitable

one is found

Page 12: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

12

An Example

// A driver for imaginary1Class.forName("ORG.img.imgSQL1.imaginary1Driver");// A driver for imaginary2Driver driver = new ORG.img.imgSQL2.imaginary2Driver();DriverManager.registerDriver(driver);//A driver for PostgreSQLClass.forName("org.postgresql.Driver");

Page 13: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

13

3. Establish the connection

Connection con = DriverManager.getConnection("jdbc:imaginaryDB1://localhost:3306/");

Page 14: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010
Page 15: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

15

4. Create a Statement object

We use Statement objects in order to Query the DB Update the DB(insert, update, create, drop, …)

Page 16: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010
Page 17: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

17

5. Execute a query using the Statement

executeQuery returns a ResultSet object representing the query result (discussed later…)

Page 18: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010
Page 19: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

19

Manipulating DB with Statement

executeUpdate is for data manipulation: insert, delete, update, create table, etc.

executeUpdate returns the number of rows modified (or 0 for DDL commands)

String deleteStr = “delete from movies where movieName=‘Movie1’ ”;

Statement stmt = con.createStatement();int rowsDeleted = stmt.executeUpdate(deleteStr);

Page 20: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

20

6. Process the result

We will discuss ResultSet in a while…

Page 21: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010
Page 22: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

22

7. Close the connection

Close Connections, Statements, and Result Sets con.close(); stmt.close(); rs.close();

‘finally’ block is a good place…

Page 23: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010
Page 24: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

24

ResultSet

ResultSet objects provide access to the tables generated as results of executing Statement queries.

Only one ResultSet per Statement can be open at a given time!

The table rows are retrieved in sequence: A ResultSet maintains a cursor pointing to its current

row. next() moves the cursor to the next row

Page 25: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

25

ResultSet Methods boolean next()

Activates the next row First call to next() activates the first row Returns false if there are no more rows Not all of the next calls actually involve the DB

void close() Disposes of the ResultSet Allows to re-use the Statement that created it Automatically called by most Statement methods

Type getType(int columnIndex) Returns the given field as the given type Indices start at 1 and not 0! Add the column name as a comment if it is known!

Type getType(String columnName) Same, but uses name of field

int findColumn(String columnName) Looks up column index given column name

Type = int || double || long || boolean || byte || time || date …

Page 26: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

26

Timeout

Use setQueryTimeOut(int seconds) of Statement class to set a timeout for the driver to wait for a query to be completed.

If the operation is not completed in the given time, an SQLException is thrown

What is it good for?

Page 27: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

27

Mapping Java Types to SQL Types

Page 28: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

28

Null Values

In SQL, NULL means the field is empty Not the same as 0 or “”!

In JDBC, you must explicitly ask if the last read field was null ResultSet.wasNull(column)

For example, getInt(column) will return 0 if the value is either 0 or NULL!

Page 29: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

29

Database Time

Times in SQL are notoriously non-standard Java defines three classes to help java.sql.Date

year, month, day java.sql.Time

hours, minutes, seconds java.sql.Timestamp

year, month, day, hours, minutes, seconds, nanoseconds

Usually use this one

Page 30: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

30

Exceptions

An SQLException is actually a list of exceptions

Page 31: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

31

Prepared Statements

The PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the

DBMS can just run the PreparedStatement SQL statement without having to compile it first.

Most often used for SQL statements that take parameters.

Page 32: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

32

Creating a PreparedStatement Object As with Statement objects, you create

PreparedStatement objects with a Connection method.

The following code create a PreparedStatement object that takes two input parameters:

Page 33: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

33

Supplying Values for PreparedStatement Parameters You need to supply values to be used in place of

the question mark placeholders (if there are any) before you can execute a PreparedStatement object. You do this by calling one of the setXXX methods defined in the PreparedStatement class.

Page 34: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

34

Example

the following line of code sets the first question mark placeholder to a Java int with a value of 75:

updateSales.setInt(1, 75);

The next example sets the second placeholder parameter to the string " Colombian":

updateSales.setString(2, "Colombian");

Page 35: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

35

Another Example

Page 36: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

36

Callable Statements

Execute a call to a database stored procedure. We will not go into details

Page 37: 1 JDBC – Java Database Connectivity CS 236369, Spring 2010

37

http://www.cs.huji.ac.il/~dbi/recitations/JDBC-PSQL-c.pdf http://java.sun.com/docs/books/tutorial/jdbc/ http://www.java-samples.com/showtutorial.php?tutorialid=202

Resources used for this presentation