JDBC –�Java DataBase Connectivity
JDBC
MM Database
2
General Architecture
Unit 3
3
Anatomy
MM Database
4
Basic steps to use a database in Java
MM Database
5
1. Establish a connection
6
2. Create JDBC statement(s)
7
Executing SQL Statements
"(SSN Integer not null, Name VARCHAR(32), " + "Marks Integer)";
stmt.executeUpdate(createLehigh);
//What does this statement do?
stmt.executeUpdate(insertLehigh);
8
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");
}
9
Close connection
10
Transactions and JDBC
11
Handling Errors with Exceptions
12
Another way to access database�(JDBC-ODBC)
13
Sample program
import java.sql.*;
class Test {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //dynamic loading of driver
String filename = "c:/db1.mdb"; //Location of an Access database
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;READONLY=true}"; //add on to end
Connection con = DriverManager.getConnection( database ,"","");
Statement s = con.createStatement();
s.execute("create table TEST12345 ( firstcolumn integer )");
s.execute("insert into TEST12345 values(1)");
s.execute("select firstcolumn from TEST12345");
14
Sample program(cont)
ResultSet rs = s.getResultSet();
if (rs != null) // if rs == null, then there is no ResultSet to view
while ( rs.next() ) // this will step through our data row-by-row
{ /* the next line will get the first column in our current row's ResultSet
as a String ( getString( columnNumber) ) and output it to the screen */
System.out.println("Data from column_name: " + rs.getString(1) );
}
s.close(); // close Statement to let the database know we're done with it
con.close(); //close connection
}
catch (Exception err) { System.out.println("ERROR: " + err); }
}
}
15
Mapping types JDBC - Java
16
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 back
rs.relative(7); / / go 7 records forward
rs.absolute(100); / / go to 100th record
…
17
JDBC 2 – Updateable ResultSet
…
Statement stmt =
con.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
String query = " select students, grade from class
where type=‘really listening this presentation☺’ “;
ResultSet rs = stmt.executeQuery( query );
…
while ( rs.next() )
{
int grade = rs.getInt(“grade”);
rs.updateInt(“grade”, grade+10);
rs.updateRow();
}
18
Metadata from DB
This information is made available through �a DatabaseMetaData object.
19
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 );
…
20
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) );
}
}
21
JDBC and beyond
22
SQLJ
// SQLJ
int n;
#sql { INSERT INTO emp VALUES (:n)};
// vs. straight JDBC
int n;
Statement stmt = conn.prepareStatement
(“INSERT INTO emp VALUES (?)”);
stmt.setInt(1,n);
stmt.execute ();
stmt.close();
23
DriverManager class
The DriverManager class acts as an interface between user and drivers. It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. The DriverManager class maintains a list of Driver classes that have registered themselves by calling the method DriverManager.registerDriver().
24
Useful methods of DriverManager class
1) public static void registerDriver(Driver driver):is used to register the given driver with DriverManager.
2) public static void deregisterDriver(Driver driver):is used to deregister the given driver (drop the driver from the list) with DriverManager.
3) public static Connection getConnection(String url):is used to establish the connection with the specified url.
4) public static Connection getConnection(String url,String userName,String password):is used to establish the connection with the specified url, username and password.
25
Connection interface
A Connection is the session between java application and database. The Connection interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be used to get the object of Statement and DatabaseMetaData. The Connection interface provide many methods for transaction management like commit(), rollback() etc.
26
Commonly used methods of Connection interface:
1) public Statement createStatement(): creates a statement object that can be used to execute SQL queries.
2) public Statement createStatement(int resultSetType,int resultSetConcurrency): Creates a Statement object that will generate ResultSet objects with the given type and concurrency.
3) public void setAutoCommit(boolean status): is used to set the commit status.By default it is true.
4) public void commit(): saves the changes made since the previous commit/rollback permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.
27
Statement interface
The Statement interface provides methods to execute queries with the database. The statement interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
28
Commonly used methods of Statement interface:
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple results.
4) public int[] executeBatch(): is used to execute batch of commands.
29
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to before the first row.
30
Commonly used methods of ResultSet interface
1) public boolean next():is used to move the cursor to the one row next from the current position.
2) public boolean previous():is used to move the cursor to the one row previous from the current position.
3) public boolean first():is used to move the cursor to the first row in result set object.
4) public boolean last():is used to move the cursor to the last row in result set object.
5) public boolean absolute(int row):is used to move the cursor to the specified row number in the ResultSet object.
31
6) public boolean relative(int row):is used to move the cursor to the relative row number in the ResultSet object, it may be positive or negative.
7) public int getInt(int columnIndex):is used to return the data of specified column index of the current row as int.
8) public int getInt(String columnName):is used to return the data of specified column name of the current row as int.
9) public String getString(int columnIndex):is used to return the data of specified column index of the current row as String.
10) public String getString(String columnName):is used to return the data of specified column name of the current row as String.
32
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query.
33
Method
public void setInt(int paramIndex, int value)-sets the integer value to the given parameter index.
public void setString(int paramIndex, String value)-sets the String value to the given parameter index.
public void setFloat(int paramIndex, float value)-sets the float value to the given parameter index.
public void setDouble(int paramIndex, double value)-sets the double value to the given parameter index.
public int executeUpdate()-executes the query. It is used for create, drop, insert, update, delete etc.
public ResultSet executeQuery()-executes the select query. It returns an instance of ResultSet.
34
Multimedia Database
What is a Multimedia DBMS?
MM Database
36
Requirements of Multimedia DBMS
MM Database
37
Requirements of Multimedia DBMS (cont.)
⇒ query support
⇒ storage support
⇒ presentation and delivery support
MM Database
38
A Sample Multimedia Scenario
MM Database
39
Possible Queries
Image Query (by example):
Image Query (by keywords):
MM Database
40
Possible Queries (cont.)
Video Query:
Heterogeneous Multimedia Query:
MM Database
41
MM Database Architectures
Based on Principle of Autonomy
different data structures
processing due to
specialized structures
data banks
MM Database
42
MM Database Architectures (cont.)
Based on Principle of Uniformity
media types
MM Database
43
MM Database Architectures (cont.)
Based on Principle of Hybrid Organization
the advantages of the
first two
data sources using their
native indexes
MM Database
44
Organizing Multimedia Data Based on the�Principle of Uniformity
MM Database
45
Example to store image in Oracle database
MM Database
46
For storing image into the database, BLOB (Binary Large Object) datatype is used in the table.
MM Database
47
Java Example to store image in the database
MM Database
48