26
JDBC

Jdbc Java Programming

Embed Size (px)

Citation preview

Page 1: Jdbc Java Programming

JDBC

Page 2: Jdbc Java Programming

• File vs Database

• JDBC

• Fundamental Steps in JDBC

• Statement,PreparedStatement,CallableStatement

• ResultSet

• Practice basic JDBC programming with simple programming

using JDBC Driver

• Understand Advance JDBC programming

Content

Page 3: Jdbc Java Programming

File vs DatabaseDBMS:

• coordinates both the physical and the logical access to the data

• reduces the amount of data duplication by ensuring that a physical piece of data is

available to all programs authorized to have access to it.

• designed to allow flexible access to data (i.e., queries)

• designed to coordinate multiple users accessing the same data at the same timeFile:

• coordinates only the physical access.

• data written by one program in a file-processing system may not be readable by

another program.

• designed to allow predetermined access to data (i.e., compiled programs).

• designed to allow one or more programs to access different data files at the same

time.

Page 4: Jdbc Java Programming

JDBC

JDBC DriverJAVA Applet/Application Database

JDBC CallDatabaseCommand

• JDBC– JDBC is a standard interface for connecting to relational databases from Java– The JDBC Classes and Interfaces are in the java.sql package– JDBC is Java API for executing SQL statements

• Provides a standard API for tool/database developers• Possible to write database applications using a pure Java API• Easy to send SQL statements to virtually any relational database

• What does JDBC do?– Establish a connection with a database– Send SQL statements– Process the results

Page 5: Jdbc Java Programming

JDBC

• Java code calls JDBC library• JDBC loads a driver • Driver talks to a particular database• An application can work with several databases by using all corresponding

drivers• Ideal: can change database engines without changing any application

code (not always in practice)

JDBC DriverJAVA Applet/Application Database

JDBC CallDatabaseCommand

Page 6: Jdbc Java Programming

Fundamental Step in JDBC

• Load the driver

• Define the connection URL

• Establish the connection• Create a Statement object• Execute a query using the Statement

• Process the result• Close the connection

Page 7: Jdbc Java Programming

Loading the Driver

• We can register the driver indirectly using the statement Class.forName(“org.postgresql.Driver");

• Class.forName loads the specified class• When Driver is loaded, it automatically

– creates an instance of itself– registers this instance with the DriverManager

• Hence, the driver class can be given as an argument of the application

Page 8: Jdbc Java Programming

8

Connecting to the Database

• 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 9: Jdbc Java Programming

Connection Driver and URLRDBMS JDBC driver name URL format

MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName

ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port Number:databaseName

DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number/databaseName

Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port Number/databaseName

Postgres org.postgresql.Driver jdbc:postgresql://hostname:port/databaseName

Access sun.jdbc.odbc.JdbcOdbcDriver

Note : Both the ":" and "@" are mandatory

Page 10: Jdbc Java Programming

Syntax:

Connection conn = DriverManager.getConnection(URL, username,

passwd);

Connection conn = DriverManager.getConnection(URL)

Connection conn = DriverManager.getConnection(URL,properties

object)

Example:import java.util.*;

String URL = "jdbc:postgresql://1.1.1.1:5432/test";

Properties info = new Properties( );

info.put( "user", "username" );

info.put( "password", "password" );

Connection conn = DriverManager.getConnection(URL, info);

Note: Remember to close connection using conn.close(); or place it in finally block

Connect to Database

Page 11: Jdbc Java Programming

Interaction with the Database

• We use Statement objects in order to– Query the database– Update the database

• Three different interfaces are used:Statement, PreparedStatement, CallableStatement

• All are interfaces, hence cannot be instantiated• They are created by the Connection

Page 12: Jdbc Java Programming

Querying with Statement

• The executeQuery method returns a ResultSet object representing the query result.

String queryStr = "SELECT * FROM tbStudent" +"WHERE name = ‘sok'";

Statement stmt = con.createStatement();ResultSet rs = stmt.executeQuery(queryStr);

Page 13: Jdbc Java Programming

Changing DB with Statement

String deleteStr = "DELETE FROM tbStudent" +"WHERE lname = ‘sok'";

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

• executeUpdate is used for data manipulation: insert, delete, update, create table, etc. (anything other than querying!)

• executeUpdate returns the number of rows modified

Page 14: Jdbc Java Programming

14

About Prepared Statements

• Prepared Statements are used for queries that are executed many times

• They are parsed (compiled) by the DBMS only once• Column values can be set after compilation• Instead of values, use ‘?’

Page 15: Jdbc Java Programming

15

Querying with PreparedStatement

String queryStr = "SELECT * FROM tbStudent" +"WHERE name= ? and id= ?";

PreparedStatement pstmt = con.prepareStatement(queryStr);

pstmt.setString(1, “sok");pstmt.setInt(2, 1);

ResultSet rs = pstmt.executeQuery();

Page 16: Jdbc Java Programming

16

Statements vs. PreparedStatements: Be Careful!

• Will this work?

• No!!! A ‘?’ can only be used to represent a column value

PreparedStatement pstmt = con.prepareStatement("select * from ?");

pstmt.setString(1, myFavoriteTableString);

Page 17: Jdbc Java Programming

ResultSet• ResultSet objects provide access to the tables

generated as results of executing a Statement queries• Only one ResultSet per Statement can be open at the

same time!• The table rows are retrieved in sequence

– A ResultSet maintains a cursor pointing to its current row – The next() method moves the cursor to the next row

Page 18: Jdbc Java Programming

ResultSet

• JDBC returns the results of a query in a ResultSet object– ResultSet object contains all of the rows which satisfied the conditions

in an SQL statement• A ResultSet object maintains a cursor pointing to its current

row of data– Use next() to step through the result set row by row

• next() returns TRUE if there are still remaining records– getString(), getInt(), and getXXX() assign each value to a Java variable

Record 1 Record 2 Record 3 Record 4

ResultSetInternal Pointer

The internal pointer starts one before the first record

Page 19: Jdbc Java Programming

19

ResultSet Example

Statement stmt = con.createStatement();

ResultSet rs = stmt.

executeQuery("select id,name from tbStudent");    

// Print the result

while(rs.next()) {

 System.out.print(rs.getInt(1) + ":");

 System.out.println(rs.getString(“name"));

}

Page 20: Jdbc Java Programming

20

ResultSet Meta-Data

ResultSetMetaData rsmd = rs.getMetaData();int numcols = rsmd.getColumnCount();

for (int i = 1 ; i <= numcols; i++) {System.out.print(rsmd.getColumnLabel(i)+" ");

}

A ResultSetMetaData is an object that can be used to get information about the properties of the columns in a ResultSet object

An example: write the columns of the result set

Page 21: Jdbc Java Programming

21

Cleaning Up After Yourself• Remember to close the Connections,

Statements, Prepared Statements and Result Sets

con.close();stmt.close();pstmt.close();rs.close()

Page 22: Jdbc Java Programming

22

Dealing With Exceptions• An SQLException is actually a list of

exceptions

catch (SQLException e) { while (e != null) {

System.out.println(e.getSQLState());System.out.println(e.getMessage());System.out.println(e.getErrorCode());e = e.getNextException();

}}

Page 23: Jdbc Java Programming

23

Transactions and JDBC• Transaction: more than one statement that must all

succeed (or all fail) together– e.g., updating several tables due to customer purchase

• If one fails, the system must reverse all previous actions• Also can’t leave DB in inconsistent state halfway through

a transaction• COMMIT = complete transaction• ROLLBACK = cancel all actions

Page 24: Jdbc Java Programming

24

Example• Suppose we want to transfer money from bank account

13 to account 72:

PreparedStatement pstmt = con.prepareStatement("update BankAccount

set amount = amount + ? where accountId = ?");

pstmt.setInt(1,-100); pstmt.setInt(2, 13);pstmt.executeUpdate();pstmt.setInt(1, 100); pstmt.setInt(2, 72);pstmt.executeUpdate();

What happens if this update fails?

Page 25: Jdbc Java Programming

25

Transaction Management

• Transactions are not explicitly opened and closed• The connection has a state called AutoCommit mode• if AutoCommit is true, then every statement is

automatically committed • if AutoCommit is false, then every statement is added to

an ongoing transaction• Default: true

Page 26: Jdbc Java Programming

26

AutoCommit

• If you set AutoCommit to false, you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback()

• Note: DDL statements (e.g., creating/deleting tables) in a transaction may be ignored or may cause a commit to occur– The behavior is DBMS dependent

setAutoCommit(boolean val)