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

Unit 2 - Database Programming

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

Unit 2 - Database Programming

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

Database Programming Unit 2

Unit 2
Database Programming
Introduction
In 1996, Sun released the first version of the JDBC (Java Database Connectivity) API.
This API lets programmers connect to a database and then query or update it, using
Structured Query Language (SQL). JDBC has become one of the most commonly used
APIs in the Java library. Java programs communicate with databases and manipulate their
data using JDBC.

The Design of JDBC


Java provides a pure Java API for SQL access along with a driver manager to allow third-
party drivers to connect to specific databases. Database vendors provide their own drivers
to plug in to the driver manager. There is a simple mechanism for registering third-party
drivers with the driver manager.
Programs written according to the API talk to the driver manager, which, in turn, uses a
driver to talk to the actual database. This means the JDBC API is all that most
programmers will ever have to deal with.

JDBC MySQL
Driver MySQL
JDBC Driver Manager

JDBC
API

Java Application JDBC Oracle


Oracle

JDBC PsotgreSQL
Driver PostgreSQL

Fig: The Design of JDBC

JDBC Driver Types:


The JDBC specification classifies drivers into the following types:
• A type 1 driver translates JDBC to ODBC and relies on an ODBC driver to
communicate with the database. Early versions of Java included one such driver,
the JDBC/ODBC bridge. Java 8 no longer provides the JDBC/ODBC bridge.
• A type 2 driver is written partly in Java and partly in native code. It communicates
with the client API of a database. When using such a driver, you must install
some platform-specific code onto the client in addition to a Java library.

Page 1
Database Programming Unit 2

• A type 3 driver is a pure Java client library that uses a database-independent


protocol to communicate database requests to a server component, which then
translates the requests into a database-specific protocol. This simplifies
deployment because the platform-specific code is located only on the server.
• A type 4 driver is a pure Java library that translates JDBC requests directly to a
database-specific protocol.
Most database vendors supply either a type 3 or type 4 driver with their database.
Furthermore, a number of third-party companies specialize in producing drivers with
better standards conformance, support for more platforms, better performance, or, in
some cases, simply better reliability than the drivers that are provided by the database
vendors. In summary, the ultimate goal of JDBC is to make possible the following:
• Programmers can write applications in the Java programming language to access
any database, using SQL statements while still following Java language
conventions.
• Database vendors and database tool vendors can supply the low-level drivers.
Thus, they can optimize their drivers for their specific products.

Typical uses of JDBC


The JDBC supports both two-tier and three-tier processing models for database access.
The two-tier model is the traditional client/server model. This model has a rich GUI on
the client and a database on the server. In this model, a JDBC driver is deployed on the
client.

Database
protocol
Client JDBC Database

However, the world is moving away from client/server toward a three-tier model or even
more advanced n-tier model. In the three-tier model, the client does not make database
calls. Instead, it calls on a middleware layer on the server that in turn makes the database
queries. The three-tier model has a couple of advantages. It separates visual presentation
(on the client) from the business logic (in the middle tier) and the raw data (in the
database). Therefore, it becomes possible to access the same data and the same business
rules from multiple clients. Communication between the client and middle tier can occur
through HTTP or another mechanism such as RMI. JDBC manages the communication
between the middle tier and the back-end database.
HTTP, Database
RMI etc. protocol

Client
(visual Middle tier JDBC Database
presentation) (business logic)

Page 2
Database Programming Unit 2

Configuring JDBC and Executing SQL Statements


Of course, you need a database program for which a JDBC driver is available. There are
many excellent choices, such as SQL Server, MySQL, Oracle, and PostgreSQL. You
must also create a database for your experimental use.
You need to gather a number of items before you can write your first database program.

Database URLs
When connecting to a database, you must use various database-specific parameters such
as host names, port numbers, and database names. JDBC uses syntax similar to that of
ordinary URLs to describe data sources. The JDBC URL for MySQL database is given
below.
"jdbc:mysql://localhost:3306/college","root",""
The general syntax is
jdbc:subprotocol:other stuff
where a subprotocol selects the specific driver for connecting to the database. The format
for the other stuff parameter depends on the subprotocol used.
Driver JAR Files
You need to obtain the JAR file in which the driver for your database is located. If you
use MySQL, you need the file mysql-connector.jar. Include the driver JAR file on the
class path when running a program that accesses the database.

Starting the Database


The database server needs to be started before you can connect to it. The details depend
on your database.

Registering the Driver Class


Many JDBC JAR files automatically register the driver class. If your driver’s JAR file
doesn’t support automatic registration, you need to find out the name of the JDBC driver
classes used by your vendor. Driver name for MySQL is:
com.mysql.jdbc.Driver
There are two ways to register the driver with the DriverManager. One way is to load the
driver class in your Java program. For example,
Class.forName("com.mysql.jdbc.Driver");
Alternatively, you can set the jdbc.drivers property. You can specify the property with a
command-line argument, such as
java –D jdbc.drivers= com.mysql.jdbc.Driver ProgramName
Or, your application can set the system property with a call such as
System.setProperty("jdbc.drivers", " com.mysql.jdbc.Driver ");
You can also supply multiple drivers; separate them with colons, for example
com.mysql.jdbc.Driver:org.postgresql.Driver

Connecting to the Database


To connect to the database, we use getConnection method that returns a Connection
object. For example,

Page 3
Database Programming Unit 2

Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root","");
After connecting to the database, you can execute different SQL statements on it.

Executing SQL Statements


To execute a SQL statement, you first create a Statement object. To create statement
object, use the Connection object that you obtained from the call to
DriverManager.getConnection. For example,
Statement stmt = conn.createStatement();
Next, place the SQL statement that you want to execute into a string and call suitable
method. The executeUpdate method returns a count of the rows that were affected by the
SQL statement, or zero for statements that do not return a row count. The executeUpdate
method can execute actions such as INSERT, UPDATE, and DELETE, as well as data
definition statements such as CREATE TABLE and DROP TABLE.
However, you need to use the executeQuery method to execute SELECT queries. When
you execute a query, you are interested in the result. The executeQuery object returns an
object of type ResultSet that you can use to walk through the result one row at a time. For
example,
String sqlStmt = "SELECT * FROM student";
ResultSet rs=stmt.executeQuery(sqlStmt);
The basic loop for analyzing a result set looks like this:
while (rs.next())
{
look at a row of the result set
}
When inspecting an individual row, you will want to know the contents of the fields. A
large number of accessor methods give you this information. For example,
String sid = rs.getString(1);
String name = rs.getStirng("SName");
There are accessors for various types, such as getString, getInt etc. Each accessor has two
forms: One takes a numeric argument and the other takes a string argument. When you
supply a numeric argument, you refer to the column with that number. For example,
rs.getString(1) returns the value of the first column in the current row.
When you supply a string argument, you refer to the column in the result set with that
name. For example, rs.getString("SName") returns the value of the column with label
Price. Each get method makes reasonable type conversions when the type of the method
doesn’t match the type of the column. For example, the call rs.getString("Roll_no")
converts the integer value of the Roll_no column to a string.

Closing Result Set, Statement and Connection


After completing the database operations, we close the result set, statement and the
connection as follows.
rs.close();
stmt.close();
conn.close();

Page 4
Database Programming Unit 2

A Complete Example
import java.sql.*;
public class MyDatabaseApplication
{
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/college","root","");
Statement stmt=conn.createStatement();
String sqlStmt = "SELECT * FROM student";
ResultSet rs=stmt.executeQuery(sqlStmt);
while(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getInt(3));
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Executing other SQL Statements


Creating Tables
String sqlStmt = "CREATE TABLE Student (SID VARCHAR(10), SName VARCHAR(50),
Roll_no INTEGER)";
stmt.executeUpdate(sqlStmt);

Entering Data into a Table


String sqlStmt = "INSERT INTO Student VALUES ('S101', 'Nawaraj',4)";
stmt.executeUpdate(sqlStmt);

Updating Data into a Table


String sqlStmt = "UPDATE Student SET Roll_no = 5 WHERE SID = 'S101'";
stmt.executeUpdate(sqlStmt);

Deleting Data from a Table


String sqlStmt = "DELETE FROM Student WHERE Roll_no = 5";

Page 5
Database Programming Unit 2

stmt.executeUpdate(sqlStmt);

Dropping a Table
String sqlStmt = "DROP table Student";
stmt.executeUpdate(sqlStmt);

Prepared Statement
The PreparedStatement interface, a sub-interface of Statement interface is used to create
prepared statement. Prepared statement is used to execute parameterized query. We can
prepare a query with a host variable and use it many times. Each host variable in a
prepared query is indicated with a ?. If there is more than one variable, you must keep
track of the positions of the ? when setting the values.
Before executing the prepared statement, you must bind the host variables to actual
values with a setXxx() method. Once all variables have been bound to values, you can
execute the prepared statement as given in the program below:

ResultSet rs = stat.executeQuery();
String sid = "S112";
int roll = 15;
String sqlStmt = "SELECT * FROM Student WHERE SID = ? AND Roll_no = ?";
PreparedStatement stmtPrepared = conn.prepareStatement(sqlStmt);
stmtPrepared.setString(1, sid);
stmtPrepared.setInt(2, roll);
ResultSet rs = stmtPrepared.executeQuery();
while(rs.next())
System.out.println(rs.getString(2));
rs.close();
stmtPrepared.close();
conn.close();
Remember: We can also create prepared statements with SQL INSERT, UPDATE and
DELETE statements.

Scrollable and Updatable Result Sets


In a scrollable result set, you can move forward and backward through a result set and
even jump to any position. In an updatable result set, you can programmatically update
entries so that the database is automatically updated.

Scrollable Result Sets


By default, result sets are not scrollable or updatable. To obtain scrollable result sets from
your queries, you must obtain a different Statement object with the method
Statement stmt = conn.createStatement(type, concurrency);
For a prepared statement, use the call

Page 6
Database Programming Unit 2

PreparedStatement stmt = conn.prepareStatement(command, type, concurrency);


The possible values of type and concurrency are:
• ResultSet.TYPE_FORWARD_ONLY – The result set is not scrollable
(default).
• ResultSet.TYPE_SCROLL_INSENSITIVE – The result set is scrollable but
not sensitive to database changes.
• ResultSet.TYPE_SCROLL_SENSITIVE – The result set is scrollable and
sensitive to database changes.
If the result set is scrollable, you can scroll both forward and backward by one row using
rs.next() and rs.previous() respectively. These method returns true if the cursor is
positioned on an actual row and false if it is positioned after the last row or before the
first row.
You can move the cursor backward or forward by a number of rows with the call
rs.relative(n). If n is positive, the cursor moves forward. If n is negative, it moves
backward. If n is zero, the call has no effect. If you attempt to move the cursor outside the
current set of rows, it is set to point either after the last row or before the first row,
depending on the sign of n. Then, the method returns false and the cursor does not move.
This method returns true if the cursor is positioned on an actual row.
Alternatively, you can set the cursor to a particular row number with rs.absolute(n)
where n is the row number. To get the current row number, call rs.getRow() method. The
first row in the result set has number 1, second row has number 2, and so on. If the return
value is 0, the cursor is either before the first row or after the last row.
The methods rs.first(), rs.last(), rs.beforeFirst(), and rs.afterLast() move the cursor to
the first, to the last, before the first, or after the last position.
Finally, the methods rs.isFirst(), rs.isLast(), rs.isBeforeFirst(), and rs.isAfterLast() test
whether the cursor is at one of these special positions.

Updatable Result Sets


If you want to edit the data in the result set and have the changes automatically reflected
in the database, create an updatable result set. Updatable result sets don’t have to be
scrollable, but if you present data to a user for editing, you usually want to allow scrolling
as well. To obtain updatable result sets, create a statement as follows:
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
The result sets returned by a call to executeQuery are then updatable. If we use,
ResultSet.CONCUR_READ_ONLY, the result set cannot be used to update the database
(default).
There are rs.updateXxx() methods for all data types that correspond to SQL types, such
as rs.updateDouble(), rs.updateString(), and so on. We specify the name or the number
of the column, then the new value for the field. The rs.updateXxx() method changes only
the row values, not the database. Finally, you must call the updateRow method to send all
updates in the current row to the database. For example,
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);

Page 7
Database Programming Unit 2

String sqlStmt = "SELECT * FROM Student";


ResultSet rs = stmt.executeQuery(sqlStmt);
while(rs.next())
{
if(rs.getString(2).equals("Anuja"))
{
rs.updateString("SName", "Nawaraj");
rs.updateRow();
}
}
rs.close();
stmt.close();
You can also call the rs.cancelRowUpdates() method to cancel the updates to the current
row.
If you want to add a new row to the database through result set, first use the
rs.moveToInsertRow() method to move the cursor to a special position, called the insert
row. Then, build up a new row in the insert row position by issuing rs.updateXxx()
method. Then, call the rs.insertRow() method to deliver the new row to the database.
Finally, call rs.moveToCurrentRow() method to move the cursor back to the position
before the call to rs.moveToInsertRow() method. For example,
rs.moveToInsertRow();
rs.updateString("SID", "S112");
rs.updateString("SName", "Ram");
rs.updateInt("Roll_no", 55);
rs.insertRow();
rs.moveToCurrentRow();
Finally, you can delete the row under the cursor using rs.deleteRow() method. This
method immediately removes the row from both the result set and the database.

Row Sets
Scrollable result sets are powerful, but they have a major drawback. You need to keep the
database connection open during the entire user interaction. However, a user can walk
away from the computer for a long time, leaving the connection occupied. That is not
good – database connections are scarce resources. In this situation, use a row set.
The RowSet interface extends the ResultSet interface, but row sets don’t have to be tied
to a database connection. Row sets are also suitable if you need to move a query result to
a different tier of a complex application, or to another device such as a cell phone. You
would never want to move a result set – its data structures can be huge, and it is tethered
to the database connection.

Constructing Row Sets


The javax.sql.rowset package provides the following interfaces that extend the RowSet
interface:

Page 8
Database Programming Unit 2

• A CachedRowSet allows disconnected operation.


• A WebRowSet is a cached row set that can be saved to an XML file. The XML
file can be moved to another tier of a web application where it is opened by
another WebRowSet object.
• The FilteredRowSet and JoinRowSet interfaces support lightweight operations on
row sets that are equivalent to SQL SELECT and JOIN operations. These
operations are carried out on the data stored in row sets, without having to make a
database connection.
• A JdbcRowSet is a thin wrapper around a ResultSet. It adds useful methods from
the RowSet interface.
There is a standard way for obtaining a row set:
RowSetFactory factory = RowSetProvider.newFactory();
CachedRowSet crs = factory.createCachedRowSet();
There are similar methods for obtaining the other row set types.

Cached Row Sets


A cached row set contains all data from a result set. Since CachedRowSet is a
subinterface of the ResultSet interface, you can use a cached row set exactly as you
would use a result set. Cached row sets confer an important benefit: You can close the
connection and still use the row set. Each user command simply opens the database
connection, issues a query, puts the result in a cached row set, and then closes the
database connection. For example,
Statement stmt = conn.createStatement();
String sqlStmt = "SELECT * FROM Student";
ResultSet rs = stmt.executeQuery(sqlStmt);
RowSetFactory factory = RowSetProvider.newFactory();
CachedRowSet crs = factory.createCachedRowSet();
crs.populate(rs);
conn.close();
while(crs.next())
{
System.out.println(crs.getString(1)+" "+crs.getString(2)+" "+crs.getInt(3));
}
rs.close();
crs.close();
stmt.close();
It is even possible to modify the data in a cached row set. Of course, the modifications
are not immediately reflected in the database; you need to make an explicit request to
accept the accumulated changes. The CachedRowSet then reconnects to the database and
issues SQL statements to write the accumulated changes. You can inspect and modify the
row set with the same methods you use for result sets. If you modified the row set
contents, you must write it back to the database by calling
crs.acceptChanges(conn);

Page 9
Database Programming Unit 2

For example,
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
String sqlStmt = "SELECT * FROM Student";
ResultSet rs = stmt.executeQuery(sqlStmt);
RowSetFactory factory = RowSetProvider.newFactory();
CachedRowSet crs = factory.createCachedRowSet();
crs.populate(rs);
while(crs.next())
{
if(crs.getString(2).equals("Anuja"))
{
crs.updateString("SName", "Nawaraj");
crs.updateRow();
}
}
crs.acceptChanges(conn);
rs.close();
crs.close();
stmt.close();
conn.close();

Exercises
1. Why do we need JDBC? Explain design of JDBC in detail.
2. How do you configure and execute SQL statements in JDBC? Explain.
3. What are the benefits of using prepared statements? How do you create and execute
prepared statements?
4. Define result set. Explain scrollable and updatable result set in detail.
5. what is row set? Compare row set with result set. How do you construct row set?
Explain.
6. Assuming your own database and tables write a program using JDBC to enter and
display data from the database. Use GUI form to enter and display data.
7. Write a program to test prepared statement with SELECT, INSERT, DELETE and
UPDATE statements.
8. Write a program test scrollable and updatable result set.
9. Write a program to test row set.

Page 10

You might also like