java database connectivity lecture1
TRANSCRIPT
-
8/3/2019 Java Database Connectivity Lecture1
1/45
JDBC
Java DataBase Connectivity
-
8/3/2019 Java Database Connectivity Lecture1
2/45
2
What is JDBC?
An API that lets you access virtually any tabular data
source from the Java programming language
JDBC Data Access API JDBC Technology Homepage
Whats an API? See J2SE documentation
Whats a tabular data source?
access virtually any data source, from relational
databases to spreadsheets and flat files. JDBC Documentation
Well focus on accessing Oracle databases
-
8/3/2019 Java Database Connectivity Lecture1
3/45
3
General Architecture
What design pattern is
implied in this
architecture?
What does it buy for us? Why is this architecture
also multi-tiered?
-
8/3/2019 Java Database Connectivity Lecture1
4/45
Part I: Overview of Databases
and Java
-
8/3/2019 Java Database Connectivity Lecture1
5/45
Databases in the Enterprise
All corporate data stored in DB
SQL standardizes format (sort of)
-
8/3/2019 Java Database Connectivity Lecture1
6/45
Database Architectures
Two-tier
Three-tier
N-tier
-
8/3/2019 Java Database Connectivity Lecture1
7/45
Two-Tier Architecture
Client connects directly to
server
e.g. HTTP, email
Pro:
simple
client-side scripting offloads
work onto the client
Con: fat client
inflexible
-
8/3/2019 Java Database Connectivity Lecture1
8/45
Three-Tier Architecture
Application Server sits between client and
database
-
8/3/2019 Java Database Connectivity Lecture1
9/45
Three-TierPros
flexible: can change one part without
affecting others
can connect to different databases withoutchanging code
specialization: presentation / business logic /
data management
can cache queries
can implement proxies and firewalls
-
8/3/2019 Java Database Connectivity Lecture1
10/45
Three-Tier Cons
higher complexity
higher maintenance
lower network efficiency more parts to configure (and buy)
-
8/3/2019 Java Database Connectivity Lecture1
11/45
N-Tier Architecture
Design your application using as many tiers
as you need
Use Object-Oriented Design techniques Put the various components on whatever
host makes sense
Java allows N-Tier Architecture, especially
with RMI and JDBC
-
8/3/2019 Java Database Connectivity Lecture1
12/45
-
8/3/2019 Java Database Connectivity Lecture1
13/45
-
8/3/2019 Java Database Connectivity Lecture1
14/45
Join example
People
name
homeaddress workaddress
Addresses
id
street
state
zip
-
8/3/2019 Java Database Connectivity Lecture1
15/45
SQL
Structured Query Language
Standardized syntax for querying
(accessing) a relational database Supposedly database-independent
Actually, there are important variations from
DB to DB
-
8/3/2019 Java Database Connectivity Lecture1
16/45
SQLSyntax
INSERT INTO table (field1, field2 )
VALUES (value1, value2 )
inserts a new record into the named table
UPDATE table SET (field1 = value1,field2 = value2 ) WHERE condition
changes an existing record or records
DELETE FROM table WHERE condition
removes all records that match conditionSELECT field1, field2 FROM table WHERE
condition
retrieves all records that match condition
-
8/3/2019 Java Database Connectivity Lecture1
17/45
-
8/3/2019 Java Database Connectivity Lecture1
18/45
Part II: JDBC Overview
-
8/3/2019 Java Database Connectivity Lecture1
19/45
JDBC Goals
SQL-Level
100% Pure Java
Keep it simple High-performance
Leverage existing database technology
why reinvent the wheel? Use strong, static typing wherever possible
Use multiple methods to express multiple
functionality
-
8/3/2019 Java Database Connectivity Lecture1
20/45
JDBC Architecture
Application JDBC Driver
Java code calls JDBC library
JDBC loads a driver
Driver talks to a particular database
Can have more than one driver -> more thanone database
Ideal: can change database engines without
changing any application code
-
8/3/2019 Java Database Connectivity Lecture1
21/45
21
-
8/3/2019 Java Database Connectivity Lecture1
22/45
The Microsoft Access
Northwind Database
22
-
8/3/2019 Java Database Connectivity Lecture1
23/45
Using Microsoft Access via
ODBC
Click Start, Settings, Control Panel, Administrative Tools, Data
Sources, System DSN, and select Add
23
-
8/3/2019 Java Database Connectivity Lecture1
24/45
Using Microsoft Access via
ODBC (Continued)
Select Microsoft Access Driver, Finish, type a name under Data
Source Name, and hit Select
24
-
8/3/2019 Java Database Connectivity Lecture1
25/45
Using Microsoft Access via
ODBC (Continued)
Navigate to the Samples directory of MS Office, select
Northwind.mdb, hit OK, then hit OK in following two windows
25
-
8/3/2019 Java Database Connectivity Lecture1
26/45
Part III: JDBC APIs
-
8/3/2019 Java Database Connectivity Lecture1
27/45
27
Basic steps to use
a database in Java
1.Establish a connection
2.Create JDBC Statements
3.Execute SQL Statements 4.GET ResultSet
5.Close connections
-
8/3/2019 Java Database Connectivity Lecture1
28/45
28
1. Establish a connection
import java.sql.*;
Load the vendor specific driver Class.forName("oracle.jdbc.driver.OracleDriver");
What do you think this statement does, and how? Dynamically loads a driver class, for Oracle database
Make the connection Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@oracle-prod:1521:OPROD",username, passwd);
What do you think this statement does?
Establishes connection to database by obtaininga Connection object
-
8/3/2019 Java Database Connectivity Lecture1
29/45
29
2. Create JDBC statement(s)
Statement stmt = con.createStatement() ;
Creates a Statement object for sending SQL statements
to the database
-
8/3/2019 Java Database Connectivity Lecture1
30/45
30
Executing SQL Statements
String createLehigh = "Create table Lehigh " +
"(SSN Integer not null, Name VARCHAR(32), " +"Marks Integer)";
stmt.executeUpdate(createLehigh);
//What does this statement do?
String insertLehigh = "Insert into Lehigh values+ "(123456789,abc,100)";
stmt.executeUpdate(insertLehigh);
-
8/3/2019 Java Database Connectivity Lecture1
31/45
31
Get ResultSet
String queryLehigh = "select * from Lehigh";
ResultSet rs = Stmt.executeQuery(queryLehigh);//What does this statement do?
while (rs.next()) {
int ssn = rs.getInt("SSN");
String name = rs.getString("NAME");
int marks = rs.getInt("MARKS");
}
-
8/3/2019 Java Database Connectivity Lecture1
32/45
32
Close connection
stmt.close();
con.close();
-
8/3/2019 Java Database Connectivity Lecture1
33/45
33
Transactions and JDBC
JDBC allows SQL statements to be grouped together into asingle transaction
Transaction control is performed by the Connection object,default mode is auto-commit, I.e., each sql statement is treated
as a transaction We can turn off the auto-commit mode with
con.setAutoCommit(false);
And turn it back on with con.setAutoCommit(true);
Once auto-commit is off, no SQL statement will be committed
until an explicit is invoked con.commit(); At this point all changes done by the SQL statements will be
made permanent in the database.
-
8/3/2019 Java Database Connectivity Lecture1
34/45
34
Handling Errors with
Exceptions
Programs should recover and leave the database in
a consistent state.
If a statement in the try block throws an exception or
warning, it can be caught in one of thecorresponding catch statements
E.g., you could rollback your transaction in a
catch { } block or close database connection
-
8/3/2019 Java Database Connectivity Lecture1
35/45
Using Microsoft Access via
ODBC (Continued)
Use sun.jdbc.odbc.JdbcOdbcDriver as the
class name of the JDBC driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
U
se "jdbc:odbc:N
orth
wind" as th
e databaseaddress, and use empty strings for the
username and password.
Connection connection =
DriverManager.getConnection("jdbc:odbc:Northwind",
"","");
35
-
8/3/2019 Java Database Connectivity Lecture1
36/45
Simple Standalone Northwind
Test
import java.sql.*;
public class NorthwindTest {
public static void main(String[] args) {
String driver =
"sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:Northwind";String username = "";
String password = "";
showEmployeeTable(driver, url,
username, password);
}
36
-
8/3/2019 Java Database Connectivity Lecture1
37/45
public static void showEmployeeTable(String driver,
String url,
String username,
String password) {try {
// Load database driver if not already loaded.
Class.forName(driver);
// Establish network connection to database.
Connection connection =DriverManager.getConnection(url,
username, password);
System.out.println("Employees\n" +
"=========");
Statement statement = connection.createStatement();
String query =
"SELECT firstname, lastname FROM employees";
// Send query to database and store results.
ResultSet resultSet = statement.executeQuery(query);
37
-
8/3/2019 Java Database Connectivity Lecture1
38/45
//Print results.
while(resultSet.next()) {
//First name
System.out.print(resultSet.getString(1) + " ");
//Last name
System.out.println(resultSet.getString(2));
}
} catch(ClassNotFoundException cnfe) {
System.err.println("Error loading driver: " + cnfe);
} catch(SQLException sqle) {
System.err.println("Error connecting: " + sqle);
}
}
38
-
8/3/2019 Java Database Connectivity Lecture1
39/45
Simple Standalone Northwind
Test: Results
Prompt> java NorthwindTest
Employees
=========
Nancy Davolio
Andrew Fuller
Janet Leverling
Margaret Peacock
Steven Buchanan
Michael SuyamaRobert King
Laura Callahan
Anne Dodsworth
39
-
8/3/2019 Java Database Connectivity Lecture1
40/45
40
Mapping types JDBC - Java
-
8/3/2019 Java Database Connectivity Lecture1
41/45
41
JDBC 2 Scrollable Result Set
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
String query = select students from class where type=not sleeping ;
ResultSet rs = stmt.executeQuery( query );
rs.previous(); / / go back in the RS (not possible in JDBC 1)
rs.relative(-5);/ / go 5 records backrs.relative(7);/ / go 7 records forward
rs.absolute(100);/ / go to 100th record
-
8/3/2019 Java Database Connectivity Lecture1
42/45
-
8/3/2019 Java Database Connectivity Lecture1
43/45
43
Metadata from DB
A Connection's database is ableto provide schema informationdescribing its tables,
its supported SQL grammar,its stored proceduresthe capabilities of this connection, and so on What is a stored procedure?
Group of SQL statements that form a logical unit
and perform a particular taskThis information is made available through
a DatabaseMetaData object.
-
8/3/2019 Java Database Connectivity Lecture1
44/45
44
Metadata from DB - example
Connection con = . ;
DatabaseMetaData dbmd = con.getMetaData();
String catalog = null;String schema = null;String table = sys%;String[ ] types = null;
ResultSet rs =dbmd.getTables(catalog , schema , table , types );
-
8/3/2019 Java Database Connectivity Lecture1
45/45
45
JDBC Metadata from RS
public static void printRS(ResultSet rs) throws SQLException
{
ResultSetMetaData md = rs.getMetaData();
// get number of columns
int nCols = md.getColumnCount();// print column names
for(int i=1; i < nCols; ++i)
System.out.print( md.getColumnName( i)+",");
/ / output resultset
while ( rs.next() ){ for(int i=1; i < nCols; ++i)
System.out.print( rs.getString( i)+",");
System.out.println( rs.getString(nCols) );
}
}