0% found this document useful (0 votes)
29 views61 pages

JDBC

Uploaded by

bemelekotsisay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views61 pages

JDBC

Uploaded by

bemelekotsisay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 61

JAVA DATABASE CONNECTIVITY

What is JDBC?
 The Java API for developing Java database applications is called
JDBC.
 JDBC stands for Java Database Connectivity.
 JDBC is the trademarked name of a Java API that supports Java
programs that access relational databases.
 JDBC provides Java programmers with a uniform interface for
accessing and manipulating a wide range of relational databases.
 Using the JDBC API, applications written in the Java can execute
SQL statements, retrieve results, present data in a user-friendly
interface, and propagate changes back to the database.
 The JDBC API can also be used to interact with multiple data
sources in a distributed, heterogeneous environment.
What is JDBC?
 JDBC is the standard method of accessing databases from Java.
 Individual database management systems require a JDBC driver to
be accessed via JDBC.
 The JDBC API uses a Driver Manager and database-specific drivers
to provide transparent connectivity to heterogeneous databases.
 The JDBC driver manager ensures that the correct driver is used to
access each data source.
 The Driver Manager is capable of supporting multiple concurrent
drivers connected to multiple heterogeneous databases.
What is JDBC?
 The JDBC API is a set of Java interfaces and classes used to write Java
programs for accessing and manipulating relational databases.
 Since a JDBC driver serves as the interface to facilitate communications
between JDBC and a proprietary database, JDBC drivers are database
specific.
 They are normally provided by the database vendors.
 You need MySQL JDBC drivers to access the MySQL database, and Oracle
JDBC drivers to access the Oracle database.
 For the Access database, use the JDBC-ODBC bridge driver included in JDK.
 ODBC is a technology developed by Microsoft for accessing databases on the
Windows platform.
 An ODBC driver is preinstalled on Windows.
 The JDBC-ODBC bridge driver allows a Java program to access any ODBC
data source.
Core JDBC Components
 The JDBC API provides a number of interfaces and classes that allow to
connect to database and process the data.
 The following are the most commonly used interfaces and classes:
 Driver: A JDBC driver is a software component enabling a Java application
to interact with a database. To connect with individual databases, JDBC
requires drivers for each database. This interface handles the
communications with the database server. You will interact directly with
Driver objects very rarely. Instead, you use DriverManager objects, which
manages driver objects. It also abstracts the details associated with working
with Driver objects.
 DriverManager: this class manages a list of database drivers. It matches
connection requests from a java application with the proper database driver
using communication subprotocol. The first driver that recognizes a certain
subprotocol under JDBC will be used to establish a database Connection.
 Connection: This interface has methods for communicating with a database.
The connection object represents communication context, i.e., all
Core JDBC Components…
 Statement: You use objects created from this interface to submit the SQL
statements to the database. The Statement interface contains the methods
necessary to send SQL statements to the database for execution and
return the results. In particular, you use the executeQuery() method to
execute a select statement or the executeUpdate() method to execute an
insert, update, or delete statement.
 ResultSet: These objects hold data retrieved from a database after you
execute an SQL query using Statement objects. It acts as an iterator to
allow you to move through its data. The ResultSet interface represents
rows returned from a query. It provides methods you can use to move
from row to row and to get the data of each column.
 SQLException: This class handles any errors that occur in a database
application.
JDBC Drivers
 A JDBC driver translates standard JDBC calls into a network or
database protocol or into a database library API call that facilitates
communication with the database.
 This translation layer provides JDBC applications with database
independence.
 If the back-end database changes, only the JDBC driver need be
replaced with few code modifications required.
 There are four distinct types of JDBC drivers:
 JDBC-ODBC bridge and ODBC driver, also called Type 1.

 Native-API, partly Java driver, also called Type 2.

 Network-protocol driver, pure Java driver, also called Type 3.

 Database-protocol driver, pure Java driver, also called Type 4.


JDBC Drivers…
JDBC Drivers…
Type 1 Driver - the JDBC-ODBC Bridge
 The JDBC type 1 driver is a database driver implementation that employs
the ODBC driver to connect to the database.
 The driver converts JDBC method calls into ODBC function calls.
 The bridge is usually used when there is no pure-Java driver available for
a particular database.
 Type 1 drivers are also known as the JDBC-ODBC bridge.
 Sun provides a JDBC-ODBC Bridge driver called sun.jdbc.odbc.JdbcOdbcDriver.
 This driver is native code which is not Java code.
 The connection flow is like:
Client -> JDBC-ODBC Bridge driver -> ODBC Driver -> Database
Type 2 Driver - the Native-API Driver
 The JDBC type 2 driver is a database driver implementation that uses the

client-side libraries of the database.


 The driver converts JDBC method calls into native calls of the database

API.
 The type 2 driver is not written entirely in Java as it interfaces with non-

Java code that makes the final database calls.


Java -> JDBC Driver -> Vendor Client DB Library -> Database
 Oracle’s OCI is an example of client-side library and Oracle JDBC driver

is a type 2 driver.
 Advantage

 Better performance than Type 1 since no JDBC to ODBC translation is

needed.
 Disadvantages

 The vendor client library needs to be installed on the client machine.

 Not all databases have the client side library.

Fig Native-API driver


JDBC Drivers…
Type 3 driver - the Network-Protocol Driver
 The JDBC type 3 driver is a database driver implementation which makes
use of a middle-tier between the calling program and the database.
 The middle-tier (application server or middleware) converts JDBC calls
directly or indirectly into the vendor-specific database protocol.
 It is also known as the network-protocol driver.
 These drivers use a pure Java code and communicate with a middleware
server using a database-independent protocol.
 The middleware server then communicates the client's requests to the data
source.

Fig Network-protocol driver


JDBC Drivers…
Type 4 - the Database-Protocol Driver
 The JDBC type 4 driver is a database driver implementation that converts
JDBC calls directly into the vendor-specific database protocol.
 The type 4 driver is written completely in Java and is hence platform
independent.
 It provides better performance over the type 1 and 2 drivers as it does not
have the overhead of conversion of calls into ODBC or database API calls.
 Unlike the type 1 and 2 drivers, it doesn’t need associated software to work.
 This is the highest performance driver available for the database and is
usually provided by the database vendor itself.
 This driver is very flexible, you don't need to install special software on the
client or server.
JDBC Drivers…
 For all examples in this chapter, we use the following table called
student.
 The name of the database is university_record.

ID firstname middlename lastname sex birthdate email phone

1234/04 Abebe Bekele Chala male 1990-10-20 [email protected] 1234567890

4321/05 John Kendall Leo male 1991-05-10 [email protected] 0987654321

... … … … … … …
Connecting to DB
 Connecting to database involves the following steps:
 Registering the driver with the DriverManager

 Connecting to the database using the registered Driver

 Executing SQL statements on the database

 Closing the connection

 Before starting this process, it is necessary to download the JDBC


driver for the specific database you want to connect to.
 Then, add the location of the drivers to the class path.
Connecting to DB…
Registering Drivers
 Before you can use JDBC to access a database, you must first establish a connection

to the database.
 The first step to establishing a connection involves registering the driver class so the

class is available.
 To do that, you use the forName method of the class Class, specifying the package

and class name of the driver.


try {
Class.forName("JDBCDriverClass");
} catch (ClassNotFoundException e) {
// Report the exception
}
 The forName method throws ClassNotFoundException if the driver class can’t be
located.
 So you have to enclose it in a try/catch block that catches ClassNotFoundException.
 For example, to register the MySQL connector, use this statement:
Class.forName("com.mysql.jdbc.Driver");
Connecting to DB…
 To register the standard ODBC driver, use this statement instead:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
 A driver class loaded in this fashion should create an instance of itself and

register it with the driver manager.


 You can also register drivers with driver manager by calling

DriverManager.registerDriver() static method.


 Before registering the driver, you have to create instance object of the driver.

 You can do this as follows:

try {
Driver myDriver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver( myDriver );
} catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Connecting to DB…
 The following table lists down popular JDBC driver names and database URL.
RDBMS JDBC driver class URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname:port/dbName

ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:portnumber:dbName

DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:portnumber/dbName

Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: portNumber/dbName

SQL com.microsoft.sqlserver.jdbc.SQLServerDriver jdbc:sqlserver://server:port;DbName=dbname

 To use the JDBC-ODBC bridge in a Java, a suitable ODBC data source must be
configured.
 The data source should be configured as a System DSN, not a User DSN.
 The driver class name is sun.jdbc.odbc.JdbcOdbcDriver if the Sun JVM is used.
 The database URL used in the getConnection() statement is jdbc:odbc:dsn, where
Connecting to DB…
Connecting to Database
 After you register the driver class, you can call the static getConnection

method of DriverManager class to open connection.


 This method takes three String parameters: the database URL, the user

name, and a password.


String url = “jdbc:mysql://localhost:3306/ university_record”;
con = DriverManager.getConnection(url, “root”, “vertrigo”);
 DriverManager provides three different methods to get connection:
DriverManager.getConnection(String url)
DriverManager.getConnection(String url, String username, String password)
DriverManager.getConnection(String url, Properties prop)
 The methods throw SQLException if a database access error occurs or the
url is null.
 They also throw SQLTimeoutException if the timeout value specified by
the setLoginTimeout method has been exceeded.
Connecting to DB…
 The key argument to DriverManager.getConnection() is a JDBC URL,
which is a string with three components separated by semicolons:
<protocol>:<subprotocol>:<subname>
 where
 protocol - is always jdbc.
 subprotocol - is a vendor-specific string that identifies the driver to
be used. The driver indicates whether it can handle that subprotocol
when asked by the driver manager. For example, the JDBC-ODBC
bridge uses the reserved value odbc as its subprotocol. This value is
intended to be unique across all driver vendors.
 subname - identifies the specific database to connect to. This string
contains whatever the driver needs to identify the database. It may
also contain connection parameters the database needs.
Connecting to DB…
 Examples of JDBC URLs are
jdbc:odbc:finance
 This would indicate an ODBC data source named finance that is
accessed by the JDBC-ODBC bridge driver.
 You can also specify like this
jdbc:idb:c:/path/database.prp
 For MySQL database, it can be specified using the following
syntax:
jdbc:mysql://server:port/databasename
 Example:
jdbc:mysql://localhost:3306/university_record
Connecting to DB…
 Example: connecting to MySQL server
Connection getConnection(){
Connection con = null;
try {
Class.forName(“com.mysql.jdbc.Driver”);
String url = “jdbc:mysql://localhost:3306/university_record”;
String user = “root”;
String pw = “vertrigo”;
con = DriverManager.getConnection(url, user, pw);
} catch (ClassNotFoundException e){
System.out.print(e.getMessage());
System.exit(0);
} catch (SQLException e){
System.out.print(e.getMessage());
System.exit(0);
}
return con;
Querying a Database
 After you establish a connection to a database, you can execute SQL
statements to retrieve data.
 To do so, you have to use several classes and interfaces:
 Connection: the Connection interface the createStatement() method that
returns a Statement object, which you then use to execute statements.
 Statement: the Statement interface contains the methods necessary to send
SQL statements to the database for execution and returning the results.
 Use the executeQuery() method to execute a select statement
 Use the executeUpdate() method to execute an insert, update, or delete
statement.
 ResultSet: the ResultSet interface represents rows returned from a query.
 It provides methods you can use to move from row to row and to get the
data for a column.
Querying a Database…
 Methods of Connection interface
Connection interface methods Description

void close() Closes the connection.

Creates a Statement object that can execute a SQL


Statement createStatement()
statement on the database connected by the connection.

Statement createStatement (int type, Creates a Statement object that can execute an SQL
int concur) statement on the database connected by the connection.

PreparedStatement
Creates PreparedStatement object that can execute an SQL
prepareStatement( String SQL, int type,
statement on the database connected by the connection
int Concur)

CallableStatement prepareCall(String
Creates a CallableStatement object
sql, int type, int Concur)
Querying a Database…
 Once you create the Statement object using one of the above
methods of Connection interface, you can now execute an SQL
statement on the database.
 Statement interface provides few methods to enable programmers to
do this.
 Statement Interface methods
Methods Description
Executes the select statement contained in the
ResultSet executeQuery(String sql) string parameter and returns the result data as a
ResultSet object.
Executes the insert, update, or delete statements
int executeUpdate(String sql) contained in the string parameter and returns the
result data as a ResultSet object.
Querying a Database…
 The createStatement method of Connection interface has the following syntax:
Statement createStatement (int type, int concur);
 The first parameter of the createStatement method specifies the type of result set
that is created, and can be one of the following:
 ResultSet.TYPE_FORWARD_ONLY - the result set cannot be scrolled; its cursor
moves forward only, from before the first row to after the last row.
 This is the default value.
 ResultSet.TYPE_SCROLL_INSENSITIVE - the result can be scrolled; its cursor
can move both forward and backward, and it can move to an absolute position.
 The result set is insensitive to changes made to the underlying data source while
it is open.
 It contains the rows that satisfy the query at either the time the query is executed
or as the rows are retrieved.
 ResultSet.TYPE_SCROLL_SENSITIVE - the result can be scrolled; its cursor
can move both forward and backward, and it can move to an absolute position.
 The result set reflects changes made to the underlying data source while the
Querying a Database…
 The second parameter is the concurrency of a ResultSet object.
 The concurrency of a ResultSet object determines what level of
update functionality is supported.
 This indicates whether the result set is read-only or updatable, and
can be one of the following:
 ResultSet.CONCUR_READ_ONLY - creates a read-only result

set. This is the default value.


 ResultSet.CONCUR_UPDATABLE - creates an updateable

result set. If insertion, updating and deletion is required, it is


necessary to open it as ResultSet.CONCUR_UPDATABLE.
Querying a Database…
 The following snippet executes a select statement and puts the
result in Resultset called rows:
Connection con = null;
try {
Class.forName(“com.mysql.jdbc.Driver”);
String url = “jdbc:mysql://localhost:3306/university_record”;
String user = “root”;
String pw = “vertrigo”;
con = DriverManager.getConnection(url, user, pw);
} catch (Exception ex){
System.out.println(ex.getMessage());
}
Statement st = con.createStatement();
String select = “Select * from student”;
Navigating through the ResultSet
 The ResultSet object returned by the executeQuery() contains all the rows that
are retrieved by the select statement.
 You can only access one of those rows at a time.
 The result set maintains a pointer called a cursor to keep track of the current
row.
 You can use the following methods to move the cursor through a result set.
Method Description
void close() Closes the Resultset
boolean next() Moves cursor to the next row
boolean previous() Moves the cursor to the previous row in the ResultSet
boolean first() Moves the cursor to the first row in the ResultSet
void last() Moves the cursor to the last row.
Moves the cursor to the front of this ResultSet object, just before the first
void beforeFirst()
row.
void afterLast() Moves the cursor to the end of the ResultSet object, just after the last row
boolean absolute(int row) Moves the cursor to the given row number in this ResultSet object.
boolean relative(int row) Moves the cursor forward or backward the number of rows specified
int getRow() Gets the current row number
boolean isBeforeFirst() True if the cursor is before the first row
boolean isAfterLast() True if the cursor is after the last row
boolean isFirst() True if the cursor is positioned on the first row
boolean isLast() True if the cursor is positioned on the last row
Querying a Database…
 boolean absolute(int row) - moves the cursor to the given row number in
this ResultSet object.
 If the row number is positive, the cursor moves to the given row number
with respect to the beginning of the result set.
 The first row is row 1, the second is row 2, and so on.
 If the given row number is negative, the cursor moves to an absolute row
position with respect to the end of the result set.
 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, etc.
 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.
 Calling absolute(1) is the same as calling first().
 Calling absolute(-1) is the same as calling last().
Connection con = null;
Statement statement = null;
ResultSet records = null;
String sql;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/university_record", "root", "vertrigo");
sql = "select * from student";
statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
records = statement.executeQuery(sql);
}catch(SQLException xx) {
out.print(“Error: " + xx.getMessage());
} catch(Exception xx) {
out.print(“Error: " + xx.getMessage());
}
while(records.next()) {
System.out.print(records.getString("ID"));
System.out.print(records.getString("firstname"));
System.out.print(records.getString("middlename"));
System.out.print(records.getString("lastname"));
System.out.print(records.getString("sex"));
System.out.print(records.getString("email"));
System.out.print(records.getInt("telephone"));
}
con.close();
6.5 Querying a Database…
 The data returned from the database can be accessed using
column number/index or column names.
 To access the columns of the database table from the
ResultSet, we use the get methods of ResultSet.
 There is a get method for every data type that can be stored in
database.
Method Description
BigDecimal getBigDecimal(String columnName)
Gets the value of the specified column as a BigDecimal
BigDecimal getBigDecimal(int columnIndex)
boolean getBoolean(String columnName)
Gets the value of the specified column as a boolean
boolean getBoolean(int columnIndex)
Date getDate(String columnName)
Gets the value of the specified column as a Date
Date getDate(int columnIndex)
double getDouble(String columnName)
Gets the value of the specified column as a double
double getDouble(int columnIndex)
float getFloat(String columnName)
Gets the value of the specified column as a float
float getFloat(int columnIndex)
int getInt(String columnName)
Gets the value of the specified column as a int
int getInt(int columnIndex)
long getLong(String columnName)
Gets the value of the specified column as a long
long getLong(int columnIndex)
short getShort(String columnName)
Gets the value of the specified column as a short
short getShort(int columnIndex)
String getString(String columnName)
Gets the value of the specified column as a String
String getString(int columnIndex)
Blob getBlob(String columnName)
returns the value of the specified column as a Blob object
Blob getBlob(String columnIndex)
byte getByte(String columnName)
Gets the value of the specified column as a byte
byte getByte(String columnIndex)
byte[] getBytes(String columnName)
Returns the value of the specified column as a byte array
byte[] getBytes(String columnIndex)
Array getArray(String columnName)
Returns the value of the specified column as an Array object
Array getArray(String columnIndex)
public class Database extends JFrame {
Connection con = null;
Statement statement = null;
ResultSet records = null;
protected void retrieveData() throws SQLException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/university_record", "root", "vertrigo");
String sql = "select * from student";
statement = con.createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
records = statement.executeQuery(sql);
//records.next();
while(records.next()) {
System.out.print(records.getString("ID") + "\t");
System.out.print(records.getString("firstname") + "\t");
System.out.print(records.getString("middlename") + "\t");
System.out.print(records.getString("lastname") + "\t");
System.out.print(records.getString("sex") + "\t");
System.out.print(records.getDate("birthdate") + "\t");
System.out.print(records.getString("email") + "\t");
System.out.print(records.getInt("phone") + "\t");
System.out.println();
}
con.close();
} catch(Exception xx) {
System.out.print(“Error querying: " + xx.getMessage());
}
Updating Database
 Besides executing select statements, you can also use a Statement
object to execute insert, update, or delete statements as well.
 To do that, you call the executeUpdate() method instead of the
executeQuery() method.
 This method returns an int value that indicates how many rows were
updated.
 You can test the return value to determine whether the data was
properly updated.
Class.forName(“com.mysql.jdbc.Driver”);
String url = “jdbc:mysql://localhost:3306/teaching”;
Connection con = DriverManager.getConnection(url, “root”, “vertrigo”);
try {
Statement stmt = con.createStatement();
sql = “insert into student values(‘1256/07’, ‘David’, ’Jacques’, ‘George’, ’Male’,
‘1980-05-20’, 8954578693567, ‘[email protected]’)”;
int i = stmt.executeUpdate(sql);
if (i == 1)
System.out.println(“Student registered.”);
else
System.out.println(“Student registration failed.”);
} catch (SQLException e){
System.out.println(e.getMessage());
System.exit(0);
}
 In addition to executing any type of update using executeUpdate() method,
the ResultSet interface provides methods that will allow to do updating
without writing any SQL statement.
 These methods make updating easier.
 The updating methods for ResultSet are:

Method Description

void cancelRowUpdates() Cancels the updates made to the current row in this ResultSet object.

Deletes the current row from this ResultSet object and from the
void deleteRow()
underlying database.
Inserts the contents of the insert row into this ResultSet object and
void insertRow()
into the database.
Moves the cursor to the remembered cursor position, usually the
void moveToCurrentRow()
current row.
void moveToInsertRow() Moves the cursor to the insert row.

void refreshRow() Refreshes the current row with its most recent value in the database.

Updates the underlying database with the new contents of the


void updateRow()
current row of this ResultSet object.
Updating Database…
Deleting Rows
 To delete the current row, call the deleteRow() method.

 This method cannot be called when the cursor is on the insert row.

 It throws an SQLException if:

 A database access error occurs

 the result set concurrency is CONCUR_READ_ONLY

 this method is called on a closed result set

 if this method is called when the cursor is on the insert row.

 Example: deleting a row

try {
rs.absolute(3);
rs.deleteRow();
}catch (SQLException e) {
out.println(e.getMessage());
Updating Database…
Updating Rows
 For a result set to be updated, it must have been produced by a
Statement object created with a concurrency type of
ResultSet.CONCUR_UPDATABLE.
 JDBC provides updateXXX() methods, where XXX is the JDBC
data type, similar to the existing getXXX() methods.
 These methods take a column number or column name parameter,
and a value parameter.
Update by Column name or index description
updateBoolean (String colname, boolean value) Updates the designated column with a boolean value. The updater methods are used
updateBoolean(int colIndex, boolean value) to update column values in the current row or the insert row.

updateDate(String colname, Date value) Updates the designated column with a java.sql.Date value. The updater methods are
updateDate(int colIndex, Date value) used to update column values in the current row or the insert row.

updateDouble (String colname, double value) Updates the designated column with a double value. The updater methods are used
updateDouble(int colIndex, double value) to update column values in the current row or the insert row.

updateFloat(String colname, float value) Updates the designated column with a float value. The updater methods are used to
updateFloat(int colIndex, float value) update column values in the current row or the insert row.

updateInt(String colname, int value) Updates the designated column with an int value. The updater methods are used to
updateInt(int colIndex, int value) update column values in the current row or the insert row.

updateLong(String colname, long value) Updates the designated column with a long value. The updater methods are used to
updateLong(int colIndex, long value) update column values in the current row or the insert row.

updateShort(String colname, short value) Updates the designated column with a short value. The updater methods are used to
updateShort(int columnIndex, short value) update column values in the current row or the insert row.

updateBigDecimal (String colname, BigDecimal value) Updates the designated column with a java.sql.BigDecimal value. The updater
updateBigDecimal(int colIndex, BigDecimal value) methods are used to update column values in the current row or the insert row.

updateString(String colname, value) Updates the designated column with a String value. The updater methods are used to
updateString(int String colIndex, String value) update column values in the current row or the insert row.

updateBlob(String columnName, Blob x) Updates the designated column with a java.sql.Blob value.The updater methods are
updateBlob(String columnIndex, Blob x) used to update column values in the current row or the insert row.

updateByte(String columnName, byte x) Updates the designated column with a byte value. The updater methods are used to
updateByte(String columnIndex, byte x) update column values in the current row or the insert row.

updateBytes(int columnName, byte x[]) Updates the designated column with a byte array value. The updater methods are
updateBytes(int columnIndex, byte x[]) used to update column values in the current row or the insert row.
Updating Database…
 The following example illustrates how to update the current row of
the ResultSet:
rs.updateString(“lastname”,”William”);
rs.updateString(“sex”, “female”);
rs.updateInt(“phone”, 3456218769)
rs.updateString(“email”, “[email protected]”);
rs.updateRow();
Updating Database…
Inserting New Rows
 New rows can be added to the result set and the underlying table with insertRow().
 This involves a special cursor position known as the insert row.
 You can add/ insert data into the insert row using the updateXXX() methods
shown above.
 The following example illustrates how this works:
rs.moveToInsertRow();
rs.updateString(“ID”, “1256/07”);
rs.updateString(“firstname”, “David”);
rs.updateString(“middlename”, “Jacques”);
rs.updateString(“lastname”, “George”);
rs.updateString(“sex”, “Male”);
rs.updateString(“email”, “[email protected]”);
rs.updateInt(“telephone”, 8954578693567);
rs.insertRow();
PreparedStatement Object
 The PreparedStatement interface extends the Statement interface which gives
you added functionality with many advantages over a generic Statement
object.
 This statement gives you the flexibility of supplying arguments dynamically.
 The Statement interface is used to execute static SQL statements that contain
no parameters.
 The PreparedStatement interface is used to execute a precompiled SQL
statement with or without parameters.
 Since the SQL statements are precompiled, they are efficient for repeated
executions.
 The main feature of a PreparedStatement object is that it is given an SQL
statement when it is created.
 The advantage to this is that the SQL statement is sent to the DBMS right
away, where it is compiled.
PreparedStatement Object…
 As a result, the PreparedStatement object contains an SQL statement
that has been precompiled.
 So, when PreparedStatement is executed, the DBMS can just run the
PreparedStatement SQL statement without having to compile it first.
 Although PreparedStatement objects can be used for SQL
statements with no parameters, you probably use them most often
for SQL statements that take parameters.
 The advantage of using SQL statements that take parameters is that
you can use the same statement and supply it with different values
each time you execute it.
 Besides, PreparedStatement can help to avoid SQL injection attack.
 Attaching parameters later on reduces the risk of malicious user
performing SQL injection attack on the program.
PreparedStatement Object…
 To create PreparedStatement object, call the prepareStatement method of
Connection interface.
 PreparedStatement prepareStatement(String sql) – creates a PreparedStatement
object for sending parameterized SQL statements to the database. It throws
SQLException.
 PreparedStatement prepareStatement(String sql, int resultType, int concurrency) –
creates a PreparedStatement object that will generate ResultSet objects with the
given type and concurrency.
 resultType – is a result set type; one of TYPE_FORWARD_ONLY,
TYPE_SCROLL_INSENSITIVE, or TYPE_SCROLL_SENSITIVE.
 concurrency – is a concurrency type; one of CONCUR_READ_ONLY or
CONCUR_UPDATABLE.
 PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) - creates
a PreparedStatement object that has the capability to retrieve auto-generated keys.
 The given constant tells the driver whether it should make auto-generated keys
available for retrieval.
 This parameter is ignored if the SQL statement is not an INSERT statement, or an
SQL statement able to return auto-generated keys.
 autoGeneratedKeys – one of Statement.RETURN_GENERATED_KEYS or
PreparedStatement Object…
 All parameters in JDBC are represented by the ? symbol, which is
known as the parameter marker.
 You must supply values for every parameter before executing the
SQL statement.
 The setXXX() methods bind values to the parameters, where XXX
represents the Java data type of the value you wish to bind to the
input parameter.
 If you forget to supply the values, you will receive an
SQLException.
 Each parameter marker is referred to by its ordinal position.
 The first marker represents position 1, the next position 2, and so
forth.
 This method differs from that of Java array indices, which start at 0.
Method description
Sets the designated parameter to the given Java String value. The driver converts this to
setString(int paramIndex, String value) an SQL VARCHAR or LONGVARCHAR value (depending on the argument's size relative to
the driver's limits on VARCHAR values) when it sends it to the database.

Sets the designated parameter to the given Java double value.The driver converts this to
setDouble(int paramIndex, double x)
an SQL DOUBLE value when it sends it to the database.

Sets the designated parameter to the given Java float value. The driver converts this to an
setFloat(int paramIndex, float x)
SQL REAL value when it sends it to the database.

Sets the designated parameter to the given Java long value. The driver converts this to an
setLong(int paramIndex, long x)
SQL BIGINT value when it sends it to the database.

Sets the designated parameter to the given Java int value. The driver converts this to an
setInt(int paramIndex, int x)
SQL INTEGER value when it sends it to the database.

Sets the designated parameter to the given Java short value. The driver converts this to an
setShort(int paramIndex, short x)
SQL SMALLINT value when it sends it to the database.

Sets the designated parameter to the given Java byte value. The driver converts this to an
setByte(int paramIndex, byte x)
SQL TINYINT value when it sends it to the database.

Sets the designated parameter to the given java.math.BigDecimal value. The driver
setBigDecimal(int paramIndex, BigDecimal x)
converts this to an SQL NUMERIC value when it sends it to the database.

Sets the designated parameter to the given Java boolean value. The driver converts this to
setBoolean(int paramIndex, boolean x)
an SQL BIT or BOOLEAN value when it sends it to the database.

Sets the designated parameter to the given java.sql.Date value. The driver converts this to
setDate(int paramIndex, Date x)
an SQL DATE value when it sends it to the database.

Sets the designated parameter to the given java.sql.Blob object. The driver converts this
setBlob (int paramIndex, Blob x)
to an SQL BLOB value when it sends it to the database.

Sets the designated parameter to the given java.sql.Array object. The driver converts this
setArray (int paramIndex, Array x)
to an SQL ARRAY value when it sends it to the database.
setNull(int paramIndex, int sqlType) Sets the designated parameter to SQL NULL.
PreparedStatement Object…
 All of the Statement object's methods for interacting with the database
execute(), executeQuery(), and executeUpdate() also work with the
PreparedStatement object.
 However, the methods are modified to use SQL statements that can take
input parameters.
Method Description
void clearParameters() Resets all of the PreparedStatment’s query parameters
Runs the prepared query against the database; this
boolean execute() method is used primarily if multiple ResultSets are
expected.
ResultSet executeQuery() Executes the prepared query.
Executes the prepared query; this method is used for
queries that do not produce a ResultSet (such as Update).
Int executeUpdate()
It returns the number or rows affected or 0 if nothing is
returned by the SQL command
PreparedStatement pstmt = null;
Connection con = null;
void insert() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo", "root", "vertrigo");
String SQL = "INSERT INTO student VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
pstmt = con.prepareStatement(SQL);
pstmt.setString(1, "4536/05");
pstmt.setString(2, "Anna");
pstmt.setString(3, "Tom");
pstmt.setString(4, "Bill");
pstmt.setString(5, "female");
pstmt.setDate(6, new Date(95,10, 25));
pstmt.setInt(7, 748538857);
pstmt.setString(8, "[email protected]");
int suc = pstmt.executeUpdate();
if (suc == 1)
System.out.print("Data inserted");
else
System.out.print("Data insertion failed");
}catch (Exception e) {
System.out.print("Error: " + e.getMessage());
}
}
PreparedStatement Object…
 Once a PreparedStatement is prepared, it can be reused again and again.
 You reuse a PreparedStatement by setting new values for the parameters
and then execute it again.
String sql = "update student set firstname=? , middlename=?, lastname=?
where id=?";
PreparedStatement pstatement = connection.prepareStatement(sql);
pstatement.setString(1, "Gary");
pstatement.setString(2, "Larson");
pstatement.setString(3, "Walter");
pstatement.setString (4, "123 ");
int rf = pstatement.executeUpdate();
pstatement.setString(1, "Chan");
pstatement.setString(2, "Lee");
pstatement.setString(3, "Huang");
pstatement.setString(4, " 456 ");
Batch Updating
 JDBC 2.0 introduced the capability to submit a group of update statements
to be executed as a batch.
 Batch Processing allows you to group related SQL statements into a batch
and submit them with one call to the database.
 In some cases, this can represent a significant performance improvement.
 When you send several SQL statements to the database at once, you reduce
the amount of communication overhead, thereby improving performance.
 A batch update is a batch of updates grouped together, and sent to the
database in one "batch", rather than sending the updates one by one.
 Sending a batch of updates to the database in one go, is faster than sending
them one by one, waiting for each one to finish.
 There is less network traffic involved in sending one batch of updates, and
the database might be able to execute some of the updates in parallel.
 The speed up compared to executing the updates one by one, can be quite
big.
Batch Updating…
 JDBC drivers are not required to support this feature.
 You should use the DatabaseMetaData.supportsBatchUpdates() method to
determine if the target database supports batch update processing.
 The method returns true if your JDBC driver supports this feature.
 The methods used in connection with batch updates are these:
 void clearBatch() - resets a batch to the empty state.
 It empties this Statement object's current list of SQL commands.

 It throws SQLException.

 void addBatch(String sql) - adds the given SQL command to the batch.
 It throws SQLException if a database access error occurs.

 int[] executeBatch() - submits the batch and collects update counts.


 It submits a batch of commands to the database for execution and if all

commands execute successfully, returns an array of update counts.


 The int elements of the array that is returned are ordered to correspond to the

commands in the batch.


 It throws SQLException, BatchUpdateException and SQLTimeoutException.
Class.forName("com.mysql.jdbc.Driver");
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost/demo", "root", "vertrigo");
Statement stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE employee (lastName VARCHAR(20), " + "firstName VARCHAR(20), age
INTEGER )");
//add insert statements to a batch
stmt.clearBatch();
stmt.addBatch("INSERT INTO employee VALUES ('Rodrigo','Joaquin',30)");
stmt.addBatch("INSERT INTO employee VALUES ('Gossec','Francois-Joseph',36)");
stmt.addBatch("INSERT INTO employee VALUES ('Ruggles','Carl',36)");
stmt.addBatch("INSERT INTO employee VALUES ('Widor','Charles’,34)");
stmt.addBatch("INSERT INTO employee VALUES ('Sibelius','Jean',23)");
stmt.addBatch("INSERT INTO employee VALUES('Copland','Aaron',21)");
stmt.addBatch("INSERT INTO employee VALUES('Auber','Daniel Francois',30)");
stmt.addBatch("INSERT INTO employee VALUES('Stravinsky','Igor',40)");
// Execute the batch and check the update counts
int[] counts = stmt.executeBatch();
boolean allGood = true;
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 1)
allGood = false;
}
if(allGood)
System.out.println(“All data inserted”);
else
System.out.println(“At least one error occurred”);
stmt.close();
Batch Updating…
 Batch can also be used with PreparedStatement in addition to Satatement.
 In this case, the compiled SQL will be added to batch and finally executed as a group.
String query = "INSERT INTO Student(ID, firstname, middlename, lastname) VALUES
(?,?,?,?)";
PreparedStatement pstatement= con.prepareStatement(query);

pstatement.setString(1, "345/06");
pstatement.setString(2, "Tesfaye");
pstatement.setString(3, "Mekonen");
pstatement.setString(4, "Getahun");
pstatement.addBatch();

pstatement.setString(1, 102);
pstatement.setString(2, “Tesfaye");
pstatement.setString(3, “Bekele");
pstatement.setString(4, “Abebe”);
pstatement.addBatch();
Retrieving Metadata
 JDBC provides the DatabaseMetaData interface for obtaining database-wide
information.
 It provides ResultSetMetaData interface for obtaining information on the
specific ResultSet.

A. DatabaseMetadata
 A connection provides access to database metadata information that describes

the capabilities of the database, supported SQL grammar, stored procedures,


and so on.
 The DatabaseMetaData interface provides information about the database

as a whole.
 There are many methods within the interface, such as whether or not

transactions are supported or whether or not JDBC 2.0-type result sets


are supported.
 These methods are very important for making a JDBC program as portable as

possible, since the use of advanced features is not supported in all


Retrieving Metadata…
 The DatabaseMetaData interface also provides a means to find
out about the schema.
 There is a method to retrieve the names of the tables
available, as well as the name of the stored procedures
available .
 There are methods to return primary keys, foreign keys, and
user-defined types.
 To obtain an instance of DatabaseMetaData for a database, use the
getMetaData method on a connection object like this:
DatabaseMetaData dbMetaData = connection.getMetaData();
Retrieving Metadata…
 DatabaseMetaData defines a number of methods that returns
different kind of information about the database.
Method description
String getURL() Returns the URL for this DBMS
String getUserName() Returns the user name as known to this database.
boolean isReadOnly() Returns whether this database is in read-only mode.
String getDatabaseProductName() Retrieves the name of this database product.
String getDatabaseProductVersion() Retrieves the version number of this database product.
String getDriverName() Retrieves the name of this JDBC driver.
String getDriverVersion() Retrieves the version number of this JDBC driver as a String.
Retrieves the maximum number of concurrent connections
int getMaxConnections()
to this database that are possible.
Retrieves the maximum number of columns this database
int getMaxColumnsInTable()
allows in a table.
Retrieves the maximum number of characters this database
getMaxTableNameLength()
allows in a table name.
 Example: using DatabaseMetaData to get information about the database
public class TestDatabaseMetaData {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost/university_record", "root", "vertrigo");
DatabaseMetaData dbMetaData = connection.getMetaData();
System.out.println("database URL: " + dbMetaData.getURL());
System.out.println("database username: " + dbMetaData.getUserName());
System.out.println("database product name: " + dbMetaData.getDatabaseProductName());
System.out.println("database product version: " + dbMetaData.getDatabaseProductVersion());
System.out.println("JDBC driver name: " + dbMetaData.getDriverName());
System.out.println("JDBC driver version: " + dbMetaData.getDriverVersion());
System.out.println("Max number of connections: " + dbMetaData.getMaxConnections());
System.out.println("MaxTableNameLength: " + dbMetaData.getMaxTableNameLength());
System.out.println("MaxColumnsInTable: " + dbMetaData.getMaxColumnsInTable());

connection.close();
}
}
Retrieving Metadata…
B. Result Set Metadata
 The ResultSetMetaData interface describes information pertaining to the
result set.
 A ResultSetMetaData object can be used to find the types and properties
of the columns in a ResultSet.
 To obtain an instance of ResultSetMetaData, use the getMetaData method
on a result set like this:
ResultSetMetaData rsMetaData = resultSet.getMetaData();
 ResultSetMetaData defines a number of methods that returns information
about the result set.
 For example, you can use the getColumnCount() method to find the
number of columns in the result and the getColumnName(int) method to
get the column names.
Retrieving Metadata…
Method Description
int getColumnCount() This returns the number of columns in this ResultSet object.
Indicates whether the designated column is automatically
boolean isAutoIncrement(int col)
numbered.

Returns the designated column's name. The first column is 1, the


String getColumnName(int col)
second is 2, etc.

Returns the designated column's suggested title for use in


printouts and displays. The suggested title is usually specified by
String getColumnLabel(int col)
the SQL AS clause. If a SQL AS is not specified, returns the same as
getColumnName(int) method.

String getTableName(int col) Returns the designated column's table name.


Retrieves the designated column's SQL type. The value returned is
int getColumnType(int col)
SQL type from java.sql.Types.

Indicates whether it is possible for a write on the designated


boolean isWritable(int col)
column to succeed.
public class ShowInTable extends JFrame{
JTable table;
Vector title = new Vector();
Vector rows = new Vector();
void showTable() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost/demo", "root", "vertrigo");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from student");
ResultSetMetaData rsMetaData = resultSet.getMetaData();
for (int i = 1; i <= rsMetaData.getColumnCount(); i++)
title.add(rsMetaData.getColumnName(i));
while (resultSet.next()) {
Vector temp = new Vector();
for (int i = 1; i <= rsMetaData.getColumnCount(); i++)
temp.add(resultSet.getObject(i));
rows.add(temp);
}
connection.close();
table = new JTable(rows, title);
JScrollPane sp = new JScrollPane(table);
sp.setPreferredSize(new Dimension(700, 200));
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
add(sp);
setTitle("Student table");
setSize(750, 300);
setVisible(true);
}
}

You might also like