Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

03 Java JDBC

Uploaded by

kolomiietsyosyp
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

03 Java JDBC

Uploaded by

kolomiietsyosyp
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

JDBC

(Java DataBase Connectivity)

Demchyna Mykola
October, 2014
Agenda
1. What is JDBC?
2. Introduction to JDBC
3. JDBC Architecture
4. Basic steps to use a database in Java
5. About Prepared Statements
6. Result Set
7. Mapping Java Types to SQL Types
8. Transactions and JDBC
9. Scrollable Result Set
10. Conclusion
11. References
1. What is JDBC

▪ What’s a JDBC?
– “An API that lets you access practically any
tabular data source from the Java
programming language”.
▪ What’s a tabular data source?
– “… access practically many data source, from
relational databases to spreadsheets and flat
files.”
2. Introduction to JDBC

▪ JDBC is used for accessing databases from


Java applications.
▪ Information is transferred from relations to
objects and vice-versa:
– databases optimized for searching;
– objects optimized for engineering.
3. JDBC Architecture

Oracle
We will Driver
use this one…
Oracle

Java MySQL
Application JDBC
Driver

MySQL
Network
DB2
Driver

DB2
JDBC Architecture (cont.)
▪ 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.
DB

Application JDBC Driver


4. Basic steps to use a database in Java

▪ 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.
Loading the Driver
▪ We can register the driver indirectly using the statement:
Class.forName("com.mysql.jdbc.Driver");
or
DriverManager.registerDriver(new
com.mysql.jdbc.Driver());
▪ Class.forName loads the specified class.
▪ When mysqlDriver 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.
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.
Connection con = DriverManager.
getConnection("jdbc:mysql://<URL>,
<user>, <pssword>");
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.
Querying with Statement
String queryStr =
"SELECT * FROM employee" +
"WHERE name = 'Ivan'";

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(queryStr);

▪ The executeQuery method returns a ResultSet


object representing the query result.
– Will be discussed later…
Changing DB with Statement
String deleteStr =
"DELETE FROM employee" +
"WHERE name = 'Artur'";

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.
5. About Prepared Statements
▪ Class PreparedStatement 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 ‘?’.
▪ Hence, prepared statements can be though of
as statements that contain placeholders to be
substituted later with actual values.
Querying with PreparedStatement

String queryStr =
"SELECT * FROM employee " +
"WHERE name = ? AND salary > ?";

PreparedStatement pstmt =
con.prepareStatement(queryStr);

pstmt.setString(1, "Ivan");
pstmt.setInt(2, 5200);

ResultSet rs = pstmt.executeQuery();
Updating with PreparedStatement

String deleteStr =
"DELETE FROM employee " +
"WHERE name = ? AND salary > ?";

PreparedStatement pstmt =
con.prepareStatement(deleteStr);

pstmt.setString(1, "Artur");
pstmt.setDouble(2, 4600);

int delnum = pstmt.executeUpdate();


Statements vs. PreparedStatements: Be Careful!

▪ Are these the same? What do they do?


String val = "abc";
PreparedStatement pstmt =
con.prepareStatement("SELECT * FROM r WHERE a=?");
pstmt.setString(1, val);
ResultSet rs = pstmt.executeQuery();

String val = "abc";


Statement stmt = con.createStatement();
ResultSet rs =
stmt.executeQuery("SELECT * FROM r WHERE a=" + val);
Statements vs. PreparedStatements: Be Careful!

▪ Will this work?

PreparedStatement pstmt =
con.prepareStatement("SELECT * FROM ?");

pstmt.setString(1, myFavoriteTableString);

▪ No!!! A ‘?’ can only be used to represent a


column value.
Timeout

▪ Use setQueryTimeOut(int seconds)


of Statement to set a timeout for the
driver to wait for a statement to be
completed.
▪ If the operation is not completed in the
given time, an SQLException is
thrown.
▪ What is it good for?
6. Result Set

▪ 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.
Result Set Methods

▪ boolean next()
– activates the next row;
– the first call to next() activates the first row;
– returns false if there are no more rows.
▪ void close()
– allows you to re-use the Statement that
created it;
– automatically called by most Statement
methods.
Result Set Methods (cont.)
▪ Type getType(int columnIndex)
– returns the given field as the given type
– indices start at 1 but 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
Example (Result Set)

Statement stmt = con.createStatement();


ResultSet rs = stmt. executeQuery("SELECT name,
salary FROM Employees");

// Print the result


while(rs.next()) {
System.out.print(rs.getString(1) + ":");
System.out.println(rs.getDouble("salary"
));
}
Result Set Meta-Data
▪ 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 name of the result set.

ResultSetMetaData rsmd = rs.getMetaData();


int numcols = rsmd.getColumnCount();

for (int i = 1 ; i <= numcols; i++) {


System.out.print(rsmd.getColumnLabel(i)+", ");
}
7. Mapping Java Types to SQL Types

SQL type Java Type


CHAR, VARCHAR, BLOB String
NUMERIC, DECIMAL java.math.BigDecimal
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT, DOUBLE double
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP, DATETIME java.sql.Timestamp
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.
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.
rs.wasNull(column)
▪ For example, getInt(column) will return 0 if the
value is either 0 or NULL!
Null Values

▪ When inserting null values into


placeholders of prepared statements:
– use the method setNull(index,
Types.sqlType);
– the SQL type code defined in
java.sql.Types.
Cleaning Up After Yourself

▪ Remember to close the Connections,


Statements, Prepared Statements and
Result Sets

con.close();
stmt.close();
pstmt.close();
rs.close()
8. 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
Transaction Management
▪ 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
AutoCommit

setAutoCommit(boolean val)
▪ If you set AutoCommit to false, you must
explicitly commit or rollback the transaction
using
– Connection.commit()
and
– Connection.rollback()
Example (Transactions)
▪ Suppose we want to transfer money from bank account 1 to account 2:

try {
con.setAutoCommit(false);
PreparedStatement pstmt =
con.prepareStatement("UPDATE BankAccount SET
amount = amount + ? WHERE accountId = ?");
pstmt.setInt(1, 300);
pstmt.setInt(2, 1);
pstmt.executeUpdate();
pstmt.setInt(1, 700); What happens if this
pstmt.setInt(2, 2); update fails?
pstmt.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback();
}
9. Scrollable Result Set
▪ Statement createStatement(int resultSetType,
int resultSetConcurrency)
resultSetType:
▪ ResultSet.TYPE_FORWARD_ONLY
– default; same as in JDBC 1.0
– allows only forward movement of the cursor
– when rs.next() returns false, the data is no longer available
and the result set is closed.
▪ ResultSet.TYPE_SCROLL_INSENSITIVE
– backwards, forwards, random cursor movement.
– changes made in the database are not seen in the result set
object in Java memory.
Scrollable Result Set (const.)
▪ ResultSet.TYPE_SCROLL_SENSITIVE
– backwards, forwards, random cursor movement.
– changes made in the database are seen in the result
set object in Java memory.
▪ ResultSet.CONCUR_READ_ONLY
– This is the default (and same as in JDBC 1.0) and
allows only data to be read from the database.
▪ ResultSet.CONCUR_UPDATABLE
– This option allows for the Java program to make
changes to the database based on new methods
and positioning ability of the cursor.
9. Scrollable Result Set
▪ public boolean absolute(int row) throws
SQLException
– If the given row number is positive, this method moves the
cursor to the given row number (with the first row numbered 1).
– If the given row number is negative, the cursor moves to an
absolute row position with respect to the end of the result set.
For example, calling the method absolute(-1) positions the
cursor on the last row; calling the method absolute(-2) moves
the cursor to the next-to-last row, and so on.
– If the row number specified is zero, the cursor is moved to before
the first row.
– An attempt to position the cursor beyond the first/last row in the
result set leaves the cursor before the first row or after the last
row.
9. Scrollable Result Set
▪ public boolean relative(int row) throws
SQLException
– Moves the cursor a relative number of rows, either
positive or negative.
– Attempting to move beyond the first/last row in the
result set positions the cursor before/after the first/last
row.
– Calling relative(0) is valid, but does not change the
cursor position.
– Calling the method relative(1) is identical to calling the
method next() and calling the method relative(-1) is
identical to calling the method previous().
Scrollable Result Set (const.)
▪ public int getRow() throws SQLException
– getRow() method retrieves the current row number (the first
row is number 1, the second number 2, and so on).
▪ public boolean first() throws SQLException
▪ public boolean last() throws SQLException
▪ public boolean previous() throws
SQLException
▪ public boolean next() throws SQLException
Exsample (Scrollable Result Set)
. . .
Statement stmt =
con.createStatement();

String query = "SELECT students FROM class


WHERE type='not sleeping' ";

ResultSet rs = stmt.executeQuery(query);

rs.previous(); // go back in the RS (not in JDBC 1…)

rs.relative(-5); // go 5 records back


rs.relative(7); // go 7 records forward
. . .
rs.absolute(100); // go to 100th record
10. Conclusion
▪ As shown, establishing a JDBC connection to an SQL
database with Java is a simple, two-step process.
▪ The process is nearly identical for all SQL databases,
and the only real differences are:
– the JDBC driver name;
– the JDBC URL used to connect to the database.
▪ JDBC can be used to connect to relational databases
from Java programs.
▪ Allows all basic CRUD operations and can handle
complex multi-tier, multi-vendor environments.
▪ Copious amounts of error handling required.
11. References
▪ JDBC Data Access API – JDBC Technology Homepage
http://java.sun.com/products/jdbc/index.html
▪ JDBC Database Access – The Java Tutorial
http://java.sun.com/docs/books/tutorial/jdbc/index.html
▪ JDBC Documentation
http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/index.html
▪ java.sql package
http://java.sun.com/j2se/1.4.2/docs/api/java/sql/package-
summary.html
▪ JDBC Technology Guide: Getting Started
http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/getstart/
GettingStartedTOC.fm.html
▪ JDBC API Tutorial and Reference (book)
http://java.sun.com/docs/books/jdbc/

You might also like