slides 5 jdbc
TRANSCRIPT
-
7/31/2019 Slides 5 JDBC
1/15
1
Database Programming(JDBC)
Lecture 5
2
Outline
Java DB Connectivity (JDBC) overview
JDBC API
Reading: http://java.sun.com/products/jdbc/overview.html
-
7/31/2019 Slides 5 JDBC
2/15
3
Embedded SQL
Direct SQL (= ad-hoc SQL) is rarelyused
In practice: SQL is embedded in someapplication code
user interaction, devices, programming
logic
SQL code is embedded into a hostlanguageusing special syntax
4
JDBC (Java DB Connectivity)
Java application
{ ...
"SELECT ... FROM ... WHERE"
... }
DBMS
-
7/31/2019 Slides 5 JDBC
3/15
5
xDBC
JDBC: standardfor Java language
ODBC: Open Data Base Connectivity
Language bindings for C/C++
6
JDBC in Practise
Java client code
JDBC
Database server
(Postgres, Oracle,
MySQL, SQL Server)
SQL statements
-
7/31/2019 Slides 5 JDBC
4/15
7
JDBC Drivers
Java
application
JDBC-
Driver manager
Native
Protocol driver
JDBC-
Net-driver
Native
API-driver
JDBC-ODBC
bridge
DB Client
library
DB-
MiddlewareODBC
DB Client
library
JDBC-API
8
Running a JDBC Application
Phase Task Relevant java.sql classes
Initialisation
Processing
Termination
Load driver
Create connection
Generate SQL statements
Process result data
Terminate connection
Release data structures
DriverManager
Connection
Statement
ResultSet etc.
Connection
Statement etc.
-
7/31/2019 Slides 5 JDBC
5/15
9
A Simple JDBC Application
loadDriver
getConnection
createStatement
execute(SQL)
Result handling
More
results ?
closeStatement
closeConnection
no
yes
import java.sql.*;
public class jdbctest {
public static void main(String args[]){try{
DriverManager.registerDriver(new com.mysql.jdbc.Driver( ));
Class.forName(com.mysql.jdbc.Driver)
Connection con = DriverManager.getConnection
("jdbc:mysql://lsir-cis-pc1:3306/iis01", "user", "passwd");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
(SELECT name, number FROM pcmtable WHERE number < 2");
while(rs.next())
System.out.println(rs.getString(1) + " (" + rs.getInt(2) + ")");stmt.close()
con.close();
} catch(Exception e){
System.err.println(e);
}}}
10
Loading of Driver
Create an instance of the driver
Register driver in the driver manager
Explicitloading
Class.forName(com.mysql.jdbc.Driver)
Several drivers can be loaded andregistered
-
7/31/2019 Slides 5 JDBC
6/15
11
Example: Oracle and JDBC
Class.forName("oracle.jdbc.driver.OracleDriver)
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@dbaprod1:1544:SHR1_PRD",
username, passwd);
12
Implicit Driver Loading Setting system property: jdbc.drivers
A colon-separated list of driver classnames.
Can be set when starting the application
java -Djdbc.drivers=org.postgresql.Driver application
Can also be set from within the Java applicationProperties prp = System.getProperties();prp.put("jdbc.drivers"
"com.mimer.jdbc.Driver:org.postgresql.Driver");
System.setProperties(prp);
The DriverManager class attempts to load all the
classes specified in jdbc.drivers when theDriverManager class is initialized.
-
7/31/2019 Slides 5 JDBC
7/15
13
Addressing Database
A connection is a session with one database Databases are addressed using a URL of the
form
"jdbc::
Examplesjdbc:mysql:database
jdbc:mysql://host/database
jdbc:mysql://host:port/database
Defaults: host=localhost, port=3306
14
Connecting to Database
Connection is establishedConnection con =
DriverManager.getConnection(URL,USERID,PWD); Connection properties (class
Properties)
Close the connectioncon.close();
-
7/31/2019 Slides 5 JDBC
8/15
15
Simple SQL Statements
Statement object for invocation
stmt = con.createStatement();ResultSet rset= stmt.executeQuery(
"SELECT address,script,type FROM worklist");
ResultSet object for result processing
16
Impedance Mismatch
Example: SQL in Java: Java uses int, char[..], objects, etc
SQL uses tables
Impedance mismatch = incompatible types Why not use only one language?
SQL cannot do everything that the host languagecan do
Solution: use cursors
-
7/31/2019 Slides 5 JDBC
9/15
17
Using Cursors
Access to tuples ResultSet object manages a cursor for tuple
access
ExampleStatement stmt=con.createStatement();
ResultSet rset=stmt.executeQuery(SELECT );
while (rset.next()) {
}
rset.close();
c1 c2 c3 c4
18
Accessing Attributes
(Columns)
Access to columns of a tuple Using column index or column name
Example
while (rset.next()) {
// return the value of the first column as a String
String address = rset.getString(1);
// return the value of the column type as a String
String type = rset.getString(type)
...
}
c1 c2 c3 c4
-
7/31/2019 Slides 5 JDBC
10/15
19
More on Cursors
Cursors can also modifya relationrset.updateString("script", "ebay");
rset.updateRow(); // updates the row in the data source
The cursor can be a scrolling one: can goforward, backwardfirst(), last(), next(), previous(), absolute(5)
We can determine the order in which the
cursor will get tuples by the ORDER BYclause in the SQL query
20
Inserting a row with Cursors
rs.moveToInsertRow(); // moves cursor to the insert row
rs.updateString(1, Lausanne"); // updates the first column of// the insert row to be Lausanne
rs.updateInt(2, 35); // updates the second column to be 35
rs.updateBoolean(3, true); // updates the third column to true
rs.insertRow();
rs.moveToCurrentRow();
-
7/31/2019 Slides 5 JDBC
11/15
21
Dynamic JDBC Statements
Variables within SQL statement Precompiledonce, multiple executions
Faster execution
PreparedStatement for invocation
PreparedStatement stmt = con.prepareStatement (
"SELECT * FROM data WHERE date = ?");stmt.setDate (1, j_date);
ResultSet rset = stmt.executeQuery();
22
SQL Data Types
For passing parameters to prepared
statements specific SQL data types are
needed
Examplejava.util.Date jd = new java.util.Date();java.sql.Date j_date = new java.sql.Date(jd.getTime());
-
7/31/2019 Slides 5 JDBC
12/15
23
Update Statements
Updates have no result setint result = stmt.executeUpdate("delete fromworklist");
Return value of executeUpdate
DDL-statement: always 0
DML-statement: number of tuples
24
Error Handling
Each SQL statement can generate
errors
Thus, each SQL method should be putinto a try-block
Exceptions are reported through
exceptions of class SQLException
-
7/31/2019 Slides 5 JDBC
13/15
25
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) {
try {
Class.forName(com.pointbase.jdbc.jdbcUniversalDriver);
} catch (ClassNotFoundException exc){System.out.println(exc.getMessage());
}
try {
Connection con =
DriverManager.getConnection(jdbc:jdbc:demo",
tux,penguin);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(SELECT * FROM data);
while (rs.next()) { process result tuples }
} catch (SQLException exc) {
System.out.println(SQLException: +
exc.getMessage());
} } }
26
Metadata
Metadata allows to develop schemaindependent applications for databases Generic output methods
Type dependent applications
Two types of metadata are accessible on result sets
on the database
-
7/31/2019 Slides 5 JDBC
14/15
27
ResultSet Metadata
java.sql.ResultSetMetaDatadescribes the structure of a result setobject
Information about a ResultSet object Names, types and access properties of
columns
28
Database Metadata
java.sql.DatabaseMetaDataprovides information about the database(schema etc.)
Information about the database Name of database
Version of database
List of all tables
List of supported SQL types
Support of transactions
-
7/31/2019 Slides 5 JDBC
15/15
29
Example
ResultSet rset = stmt.executeQuery(SELECT * FROMdata);
ResultSetMetaData rsmeta = rset.getMetaData();
int numCols = rsmeta.getColumnCount();
for (int i=1; i