Unit 2 - Database Programming
Unit 2 - Database Programming
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.
JDBC MySQL
Driver MySQL
JDBC Driver Manager
JDBC
API
JDBC PsotgreSQL
Driver PostgreSQL
Page 1
Database Programming Unit 2
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
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.
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.
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);
}
}
}
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.
Page 6
Database Programming Unit 2
Page 7
Database Programming Unit 2
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.
Page 8
Database Programming Unit 2
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