lec10-JDBC
lec10-JDBC
lec10-JDBC
1
Desktop Serverless Architecture
User
SQLite:
• One data file
• One user
DBMS • One DBMS application
Application
(SQLite) • Scales well!
• But only a limited number of
scenarios work with such model
• (Can be in browser / phone!)
File
Data file
Disk 6
Client-Server Architecture
Supports many apps and
many users simultaneously Client
Server Machine Applications
File 1
Connection (JDBC, ODBC)
File 2
File 3
DB Server
• One server running the database
• Many clients, connecting via the ODBC or JDBC
(Java Database Connectivity) protocol
3
Client-Server
• One server that runs the DBMS (or RDBMS):
– Your own desktop, or
– Some beefy system, or
– A cloud service (SQL Azure)
• Many clients run apps and connect to DBMS
– Microsoft’s Management Studio (for SQL Server), or
– psql (for postgres)
– Some Java program (HW8) or some C++ program
• Clients “talk” to server using JDBC/ODBC
protocol
4
3-Tiered Architecture
Browser
File 1
Connection
File 2 (e.g., JDBC)
HTTP/SSL
File 3
DB Server App+Web Server
Web-based applications
5
3-Tiered Architecture
Replicate
App server for
scale up
Connection
File 2 (e.g., JDBC)
HTTP/SSL
File 3 App+Web Server
DB Server
Slide 7
How to download a database driver
For MySQL databases, you can download a JDBC driver named
Connector/J from the MySQL web site. This driver is an open-
source, type-4 driver that’s available for free.
For other databases, you can usually download a type-4 JDBC
driver from the database’s web site.
Slide 8
Database URL syntax
jdbc:subprotocolName:databaseURL
Slide 9
How to connect to an Oracle database with
automatic driver loading
Connection connection = DriverManager.getConnection(
"jdbc:oracle:thin@localhost/murach", "scott",
"tiger");
Slide 10
How to connect to a database
You use the getConnection method of the DriverManager class to
return a Connection object.
When you use the getConnection method, you must supply a URL
for the database, a username, and a password. This method throws
a SQLException.
With JDBC 4.0, the SQLException class implements the Iterable
interface.
With JDBC 4.0, the database driver is loaded automatically. This
new feature is known as automatic driver loading. Prior to JDBC
4.0, you needed to use the forName method of the Class class to
load the driver. This method throws a ClassNotFoundException.
The connection string for each driver is different, so see the
documentation for details.
It’s possible (though not typical) to load multiple database drivers
and establish connections to multiple types of databases. Slide 11
How to create a result set that contains 1 row and
1 column
Statement statement = connection.createStatement();
ResultSet userIDResult = statement.executeQuery(
"SELECT UserID FROM User " +
"WHERE EmailAddress = 'jsmith@gmail.com'");
Slide 12
How to move the cursor to the first record in the
result set
boolean userIDExists = userIDResult.next();
Slide 13
ResultSet methods for forward-only, read-only
result sets
Method Description
next() Moves the cursor to the next row in the result set.
last() Moves the cursor to the last row in the result set.
close() Releases the result set’s resources.
getRow() Returns an int value that identifies the current row of
the result set.
Slide 14
How to return a result set and move the cursor
through it
To return a result set, you use the createStatement method of a
Connection object to create a Statement object. Then, you use the
executeQuery method of the Statement object to execute a
SELECT statement that returns a ResultSet object.
By default, the createStatement method creates a forward-only,
read-only result set. This means that you can only move the
cursor through it from the first record to the last and that you
can’t update it.
When a result set is created, the cursor is positioned before the
first row. Then, you can use the methods of the ResultSet object
to move the cursor.
The createStatement, executeQuery, and next methods throw an
SQLException. As a result, any code that uses these methods
needs to catch or throw this exception.
Slide 15
Methods of a ResultSet object that return data
from a result set
Method Description
getXXX(int columnIndex) Returns data from the specified
column number.
getXXX(String columnName) Returns data from the specified
column name.
Slide 16
Code that uses column indexes to return fields from
the products result set
String code = products.getString(1);
String description = products.getString(2);
double price = products.getDouble(3);
Slide 18
How to use the executeUpdate method to modify
data
How to add a record
String query =
"INSERT INTO Product (ProductCode,
ProductDescription, ProductPrice) " +
"VALUES ('" + product.getCode() + "', " +
"'" + product.getDescription() + "', " +
"'" + product.getPrice() + "')";
Statement statement = connection.createStatement();
int rowCount = statement.executeUpdate(query);
How to update a record
String query = "UPDATE Product SET " +
"ProductCode = '" + product.getCode() + "', " +
"ProductDescription = '" + product.getDescription() +
"', " +
"ProductPrice = '" + product.getPrice() + "' " +
"WHERE ProductCode = '" + product.getCode() + "'";
Statement statement = connection.createStatement();
int rowCount = statement.executeUpdate(query); Slide 19
How to use the executeUpdate method to modify
data (cont.)
How to delete a record
String query = "DELETE FROM Product " +
"WHERE ProductCode = '" + productCode +
"'";
Statement statement = connection.createStatement();
int rowCount = statement.executeUpdate(query);
Returns an int value that identifies the number of records that were
affected by the SQL statement.
Slide 20
How to use a prepared statement
To return a result set
String preparedSQL = "SELECT ProductCode,
ProductDescription, ProductPrice "
+ "FROM Product WHERE ProductCode = ?";
PreparedStatement ps =
connection.prepareStatement(preparedSQL);
ps.setString(1, productCode);
ResultSet product = ps.executeQuery();
Slide 21
How to use a prepared statement (cont.)
To modify data
String preparedSQL = "UPDATE Product SET "
+ " ProductCode = ?, "
+ " ProductDescription = ?, "
+ " ProductPrice = ?"
+ "WHERE ProductCode = ?";
PreparedStatement ps =
connection.prepareStatement(preparedSQL);
ps.setString(1, product.getCode());
ps.setString(2, product.getDescription());
ps.setDouble(3, product.getPrice());
ps.setString(4, product.getCode());
ps.executeUpdate();
Slide 22
How to use a prepared statement (cont.)
To insert a record
String preparedQuery =
"INSERT INTO Product (ProductCode,
ProductDescription, ProductPrice) "
+ "VALUES (?, ?, ?)";
PreparedStatement ps =
connection.prepareStatement(preparedQuery);
ps.setString(1, product.getCode());
ps.setString(2, product.getDescription());
ps.setDouble(3, product.getPrice());
ps.executeUpdate();
Slide 23
How to use a prepared statement (cont.)
To delete a record
String preparedQuery = "DELETE FROM Product "
+ "WHERE ProductCode = ?";
PreparedStatement ps =
connection.prepareStatement(preparedQuery);
ps.setString(1, productCode);
ps.executeUpdate();
Slide 24
How to work with prepared statements
When you use prepared statements in your Java programs, the
database server only has to check the syntax and prepare an
execution plan once for each SQL statement. This improves the
efficiency of the database operations.
To specify a parameter for a prepared statement, type a question
mark (?) in the SQL statement.
To supply values for the parameters in a prepared statement, use
the set methods of the PreparedStatement interface.
To execute a SELECT statement, use the executeQuery method.
To execute an INSERT , UPDATE, or DELETE statement, use
the executeUpdate method.
Slide 25