0% found this document useful (0 votes)
5 views

Java Database Connectivity

Uploaded by

Abenzer Mulugeta
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java Database Connectivity

Uploaded by

Abenzer Mulugeta
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 39

1

Why Java for Database


Programming?
Java programs can communicate with databases and
manipulate their data using the JDBC™ API.
Java is the language of choice for database
programming because of the following reasons.
1.First, Java is platform independent. You can develop
platform-independent database applications using
SQL and Java for any relational database systems.
2.Second, the support for accessing database
systems from Java is built into Java API, so you can
create database applications using all Java code with
a common interface.
3.Third, Java is taught in almost every university
either as the first programming language or as the
2
second programming language.
What Is The JDBC?
JDBC is a Java Database Connectivity API that lets you
access virtually any tabular data source from a Java
application.
JDBC defines a low-level API designed to support basic
SQL functionality independently of any specific SQL
implementation.
#.N.B:-This means the focus is on executing raw SQL
statements and retrieving their results.
In addition to providing connectivity to a wide range of
SQL databases, JDBC allows you to access other tabular
data sources such as spreadsheets or flat files .
The JDBC API includes two packages: java.sql, known as
the JDBC core API; and javax.sql, known as the JDBC
Standard Extension. Together, they contain the
necessary classes to develop database applications
using Java.
3
The Structure of JDBC
JDBC accomplishes its goals through a set of Java
interfaces
The set of classes that implement the JDBC interfaces
for a particular database engine is called a JDBC driver.
JDBC driver is an implementation of the JDBC
interface(java.sql.Driverinterace).
It communicates with particular database.
JDBC Database
calls JDBC
JDBC
JDBC command
Java app Database
Database
Database
driver
driver
driver
s

In building a database application, you do not have to


think about the implementation of these underlying
classes at all;
#N.B:-the whole point of JDBC is to hide the
specifics of each database and let you worry about
4 just your application.
The Structure of JDBC…
The relationships between Java programs,
JDBC API, JDBC drivers, and relational
databases are shown below:

5
Developing Database Applications
Using JDBC
##.The JDBC API consists of classes and interfaces
for
establishing connections with databases,
sending SQL statements to databases,
processing the results of the SQL statements, and
obtaining database metadata.
Four key interfaces are needed to develop any
database application using Java:
Driver,
Connection,
Statement, and
ResultSet
The JDBC API defines these interfaces.
The JDBC driver vendors provide implementation
6
for them.
Developing Database …
The relationship of these interfaces is shown
below

7
Developing Database …
A JDBC application loads an appropriate driver
using the Driver interface.
Connection to the database will be taken place
using the connection interface,
Creating and executing SQL statements will be
taken place using the Statement interface.
N.B.And the result will be processed using the
ResultSet interface if the statements return
results.
Note. that some statements, such as SQL data
definition statements and SQL data
modification statements, do not return results.
8
Developing Database …
A typical Java program takes the steps
outlined below to access the database.
Loading Drivers
An appropriate driver must be loaded using the
statement shown below before connecting to a
database.
Class.forName("JDBCDriverClass");
# N.B:-A driver is a concrete class that
implements the java.sql.Driver interface.
The drivers for Access, MySQL, and Oracle are
listed below:

9
Developing Database …
Establishing connections
To connect to a database, use the static
method getConnection(databaseURL) in the
DriverManager class, as follows:
Connection con =
DriverManager.getConnection(databaseURL);Wher
e
# N.B. database URL is the unique
identifier of the database .

10
Developing Database …
For example, the following statement creates a
Connection object for the local MySQL database test:
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost/test");
The databaseURL for an Oracle database specifies
the hostname, the port# where the database listens for
incoming connection requests, and the oracle DBSID
database name to locate a database.
For example, the following statement creates a
Connection object for the Oracle database on
ef.uog.edu with username fedlu and password 1234:

11
Developing Database …
Connection con =
DriverManager.getConnection
(“jdbc:oracle:thin:@ ef.uog.edu:15
21:oradb”,”fedlu”,”1234”);
Connection Methods
Statement createStatement()
returns a new Statement object
PreparedStatement
prepareStatement(String sql)
returns a new PreparedStatement object
CallableStatement prepareCall(String sql)
returns a new CallableStatement object
12
Developing Database …
Creating statements
If a Connection object can be envisioned as
a cable linking your program to a database,
##.an object of Statement or its subclass
can be viewed as a cart that delivers SQL
statements for execution by the database
and brings the result back to the program.
Once a Connection object is created, you
can create statements for executing SQL
statements as follows:

Statement stmnt =
13 connection.createStatement();
Developing Database …
Executing statements
The Structured Query Language (SQL) , Data Definition

Language (DDL) or update statement can be executed


using executeUpdate(String sql), and an SQL query
statement can be executed using executeQuery(String sql).
 The result of the query is returned in ResultSet.

 Examples:

stmnt.executeUpdate("create table Student (name char(10),

id char(5), dept char(20))");


ResultSet r= stmnt.executeQuery("select name, id, dept

from Student where name “ + " =


14‘sara'");
Developing Database …
Statement Methods
# N.B:-A Statement object is used for executing a
static SQL statement,executing sqlquery(view
statment),update statement(insert,delete,update
statement) and obtaining the results produced by it.
ResultSet executeQuery(String)
Execute a SQL statement that returns a single
ResultSet.(used for display or view result on the
consule)
int executeUpdate(String)
Execute a SQL INSERT, UPDATE or DELETE statement.
Returns the number of rows changed.
boolean execute(String)
Execute a SQL statement that may return multiple
results.
15 An more…
Developing Database …
Processing ResultSet
The ResultSet maintains a table whose
current row can be retrieved.
The initial row position is null.
You can use the next() method to move to the
next row and the various get() methods to
retrieve values from a current row.
For example, the code given below displays
all the results from the preceding SQL query.

16
Developing Database …
The getString(1), getString(2), and getString(3)
methods retrieve the column values for name, id,
and dept, respectively.

Alternatively, you can use getString(“name"),


getString(“id"), and getString(“dept") to retrieve
the same three column values.

The first execution of the next() method sets the


current row to the first row in the result set, and
subsequent invocations of the next() method set
the current row to the second row, third row, and
so on, to the last row.
17
Developing Database …
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
void close()
disposes of the ResultSet
allows you 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
18 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
Other Methods
String getString(int columnIndex)
boolean getBoolean(int columnIndex)
byte getByte(int columnIndex)
short getShort(int columnIndex)
int getInt(int columnIndex)
long getLong(int columnIndex)
float getFloat(int columnIndex)
double getDouble(int columnIndex)
Date getDate(int columnIndex)
Time getTime(int columnIndex)
19
Timestamp getTimestamp(int columnIndex)
Developing Database …
Close Connection to Database
Close the ResultSet object
rs.close();

Close the Statement object


stmt.close();

Close the connection


conn.close();

20
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class OracleJDBC {
public static void main(String[] argv)
{ System.out.println("-------- Oracle JDBC Connection
Testing ------");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace(); return; }
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
try {
connection =
DriverManager.getConnection( "jdbc:oracle:thin:
@localhost:1521:XE", “fedlu", “1234");
} catch (SQLException e)
{ System.out.println("Connection Failed! Check
output console"); e.printStackTrace(); return;
} if (connection != null)
System.out.println("You made it, take control your
database now!");
else
System.out.println("Failed to make connection!");
}
}
Additional Example
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","o
racle");
//step3 create the statement object
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * fro
m emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getStr
ing(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
}catch(Exception e)
{ System.out.println(e);}
}
}
Obtaining Object Descriptions
If you want to know the MySql database name and version, or
the JDBC driver name and version, as well as other information
like maximum numbers of columns you can get them through
the DatabaseMetaData object as shown in the following
sample program:
import java.sql.*;
public class JMySqlDatabaseInfo {
public static void main(String [] args) {
Connection con = null;
try {
Class.forName(“com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
“jdbc:mysql://localhost/student_record",
"root","");
// Database and driver info
DatabaseMetaData meta = con.getMetaData();
System.out.println("Server
25
name: “ +
System.out.println("Server version: "+
meta.getDatabaseProductVersion());
System.out.println("Driver name: " +
meta.getDriverName());
System.out.println("Driver version: " +
meta.getDriverVersion());
System.out.println("JDBC major version: "+
meta.getJDBCMajorVersion());
System.out.println("JDBC minor version: "+
meta.getJDBCMinorVersion());
System.out.println("database URL: " +
meta.getURL());
System.out.println("MaxColumnsInTable: " +
new
Integer(meta.getMaxColumnsInTable()));
System.out.println("MaxTableNameLentgh: " +
new
Integer(meta.getMaxTableNameLength()));
26 con.close();
} catch (Exception e) {
Obtaining Object Descriptions
• The output of the code in slide 30 and 31
is shown below
Server name: MySQL
Server version: 5.5.8-log
Driver name: MySQL-AB JDBC Driver
Driver version: mysql-connector-java-5.1.16 ( Revision:
${bzr.revision-id} )
JDBC major version: 4
JDBC minor version: 0
database URL: jdbc:mysql://localhost/student_record
MaxColumnsInTable: 512
MaxTableNameLentgh: 64

27
About Prepared Statements
Prepared Statements are used for
queries that are executed many times
They are parsed (compiled) by the
DBMS only once
Instead of values, use ‘?’
#N.B.Hence, Prepared Statements can
be though of as statements that contain
placeholders to be substituted later with
actual values
28
Querying with PreparedStatement
String queryStr =
"SELECT * FROM employee " +
"WHERE superssn= ? and salary > ?";

PreparedStatement pstmt =
con.prepareStatement(queryStr);

pstmt.setString(1, "333445555");
pstmt.setInt(2, 26000);

ResultSet rs = pstmt.executeQuery();
29
ResultSet
objects provide access to the tables
 ResultSet

generated the results of executing a Statement


queries
#N.B.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
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

void close()
disposes of the ResultSet
allows you to re-use the Statement that created it
automatically called by most Statement methods
ResultSet Methods
 Type getType(int columnIndex)
returns the given field as the given type
indices start at 1 and not 0!
 Type getType(String columnName)
same, but uses name of field
less efficient

For example: getString(columnIndex), getInt(columnName),


getTime, getBoolean, getType,...
 int findColumn(String columnName)
looks up column index given column name
ResultSet Example
Statement stmt = con.createStatement();
ResultSet rs = stmt.
executeQuery("select lname,salary from Employees");
// Print the result
while(rs.next()) {
System.out.print(rs.getString(1) + ":");
System.out.println(rs.getDouble(“salary"));
}

33
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

34
Transaction Management
Transactions are not explicitly(separately)
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
35
Scrollable ResultSet
 Statement createStatement( int resultSetType, int
resultSetConcurrency)
 resultSetType:
 ResultSet.TYPE_FORWARD_ONLY
 --allows only forward movement of the cursor
 -when rset.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.
 ResultSetTYPE_SCROLL_SENSITIVE
 -backwards, forwards, random cursor movement.
 -changes made in the database are seen in the

result set object in Java memory. 36


Scrollable ResultSet
(cont’d)
 resultSetConcurrency:
 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.
 Example:
 Statement stmt =
conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
 ResultSetrset= stmt.executeQuery( “SHOW TABLES”);

37
Scrollable ResultSet
(cont’d)
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 row number is negative, the cursor moves to a relative position
from the last row.
 -If the row number is 0, an SQLException will be raised .

public boolean relative(int row) throws SQLException


 This method call moves the cursor a relative number of rows, either
positive or negative.
public boolean first() throws SQLException
public boolean last() throws SQLException
public boolean previous() throws SQLException
public boolean next() throws SQLException

38
Scrollable ResultSet
(cont’d)
public void beforeFirst() throws SQLException
public void afterLast() throws SQLException
public boolean isFirst() throws SQLException
public boolean isLast() throws SQLException
public boolean isAfterLast() throws
SQLException
public boolean isBeforeFirst() throws
SQLException

39

You might also like