2. Learning Outcomes
• At the end of this presentation, you will be
able to:
– Explain JDBC and ODBC database access
– Identify JDBC driver
– Explain JDBC Statement Objects:
– Use JDBC for database connectivity
3. Java Database Connectivity (JDBC)
• Application Programming Interface (API) that allows
Java applications to access database management
systems using SQL .
• Allows java applications to connect to a relational
database
Java
application DB
JDBC
4. Java Database Connectivity (JDBC)
• JDBC helps you to write java applications that manage
these three programming activities:
i. Connect to a data source, like a database
ii. Send queries and update statements to the
database
iii. Retrieve and process the results received
from the database in answer to your query
7. Open Database Connectivity (ODBC)
• API for accessing data base/files.
• Defined by Microsoft Corporation as a standard interface
to database management systems on Windows
operating systems.
• In addition, ODBC is now widely used on many non-
Windows platforms, such as UNIX and Macintosh
8. • ODBC is composed of 4 main components:
1. the client application
2. ODBC driver manager - manages the
communications between the user applications and
ODBC Drivers
3. ODBC drivers
4. ODBC data source
10. Type 1- JDBC-ODBC bridge
• It is used for local connection.
• Use the Open Database Connectivity (ODBC) driver to
connect to the database.
• ODBC must be installed on the computer and
the database which is being connected to must support an
ODBC driver.
Load and Register the JDBC driver:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connect to database:
Connection con = DriverManager.getConnection( "jdbc:odbc:Semester6",
"abc", "1234");
DSN (Data Source
Name)
11. JDBC loads a
driver which
talks to the
database ODBC Driver Manager
DSN (data source name):
The collection of information
used to connect your
application to a particular
ODBC database. The ODBC
Driver Manager uses this
information to create a
connection to the database.
12. Configure Driver
– ODBC use Microsoft Product for database
which is Microsoft Access.
– Go to the Administrative Tools in Control
Panel.
17. • If you are running a 64-bit operating system, and you
would like to set up a 32-bit ODBC datasource, there is a
different location from which the Data Sources control
panel must be launched.
• C:WindowsSysWOW64odbcad32.exe
18.
19.
20. Advantage
• The JDBC-ODBC Bridge allows access to almost any
database, since the database's ODBC drivers are already
available.
Disadvantages
• A performance issue - JDBC call goes through the bridge to
the ODBC driver, then to the database, and this applies even
in the reverse process. They are the slowest of all driver
types.
• The client system requires the ODBC Installation to use the
driver.
• Not good for the Web.
21. • This driver is specific to a particular database - once you
switch from one database to another you need to change
type 2 JDBC driver.
• Requires installation/configuration on client machines.
• Example: Oracle OCI will have oracle OCI native API.
• Example driver: Intersolv Oracle Driver, WebLogic
drivers, Oracle OCI
Type 2- Native-API
22. Load and Register the JDBC driver:
Class.forName("oracle.jdbc.driver.OracleDriver");
Connect to database:
Connection conn =
DriverManager.getConnection("jdbc:oracle:oci8:scott/
tiger@myhost);
User: scott
Password: tiger
host: myhost
hostname is the nickname that is given to a
device connected to a computer network.
23. Advantages
• Better performance than the JDBC-ODBC Bridge as the layers of
communication (tiers) are less than that of Type 1.
• Uses Native API which is Database specific.
Disadvantages
• Native API must be installed in the Client System and hence type 2
drivers cannot be used for the Internet.
• Like Type 1 drivers, it’s not written in Java Language which forms a
portability issue - The type 2 drivers make use of the native library
and these libraries are specific to a platform. Cannot use the same
driver in different platform.
• If we change the Database we have to change the native API
as it is specific to a database
24. Type 3-JDBC-Net
• Type 3 database requests are passed through the
network to the middle-tier server.
• The middle-tier then translates the request to the
database
• e.g. Symantec DBAnywhere, Simba
25. Load and Register the JDBC driver:
Class.forName("com.jw.client.JWDriver");
RMI – Remote Method Invocation
26. Advantages
• This driver is server-based, no need for any vendor database
library to be present on client machines.
• This driver is fully written in Java - portable.
• It is suitable for the web.
• Fast to load.
• Provides support for features such as
– caching (connections, query results, and so on)
– load balancing
– advanced system administration such as logging and auditing.
• Allows access to multiple databases using one driver.
28. Type 4 - Native-protocol
• The Type 4 uses java networking libraries to
communicate directly with the database server.
– Eg: oracle, mysql, db2
• Type 4 drivers are entirely written in Java that
communicate directly with a vendor's database through
socket or port connections
29. Load and Register the JDBC driver:
Class.forName("oracle.jdbc.driver.OracleDriver");
Connect to database:
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:3306:roseindia",
“abc", “1234");
Host: localhost is the host
Port: 3306 is the port
Database: roseindia
Username: abc
Password: 1234
30. Advantages
• Completely written in Java to achieve platform
independence - most suitable for the web.
• Number of translation layers is very less - performance is
typically quite good.
• You don’t need to install special software on the client or
server.
Disadvantage
• User needs a different driver for each database.
32. A Simple JDBC application
import java.sql.*;
public class jdbctest {
public static void main(String args[]){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver “);
Connection con = DriverManager.getConnection
("jdbc:odbc:pcmtable", "user", "passwd");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
("select name, number from table 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);
}}}
loadDriver
getConnection
createStatement
execute(SQL)
Result handling
More
results ?
closeStatment
closeConnection
no
yes
33. 33
Use JDBC For Database Connectivity By
Applying The Appropriate Steps As
Follows:
1. Load the driver
2. Define the connection
3. Establish a connection
4. Create JDBC Statements
5. Execute SQL Statements
6. Process the result
7. Close connections
34. Packages to Import
• Import the following packages:
– java.sql.*; (usually enough)
– javax.sql.* (for advanced features, such as
scrollable result sets)
• A scrollable result set allows the cursor to be
moved to any row in the result set
35. 1. Load the driver
• Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
• Load the vendor specific driver for Jdbc-Odbc
driver
• Calling Class.forName, automatically
• registers the driver with the DriverManager
• The task of the DriverManager class is to keep
track of the drivers that are available and
handles establishing a connection between a
database and the appropriate driver.
36. 2. Define the connection
• import java.sql.Connection;
• Connection con;
– connect to a database
37. 3. Establish the connection
• import java.sql.DriverManager;
• Syntax
– con = DriverManager.getConnection(url,
username, passwd);
• Example
– con = DriverManager.getConnection
( "jdbc:odbc:Semester6", "abcd", "1234");
• What do you think this statement does?
• establishes connection to database by obtaining
a Connection object
38. 38
4. Create JDBC statement(s)
• Statement stmt = con.createStatement() ;
• Creates a Statement object for sending SQL statements
to the database
41. Prepared Statement
• Execute precompiled sql queries with or without
parameters.
• is used for executing parametric query
• Creating a PreparedStatement Object
PreparedStatement updateSales =
con.prepareStatement( "UPDATE COFFEES SET
SALES = ? WHERE COF_NAME LIKE ‘Colombian’")
42. Callable Statement
• Execute a call to a database stored procedure
• The stored procedure contains the SQL query to be
executed on the database and is stored on the
database.
• The following code puts the SQL statement into a
string and assigns it to the variable createProcedure,
String createProcedure = "create procedure
SHOW_SUPPLIERS " + "as " + "select
SUPPLIERS.SUP_NAME, COFFEES.COF_NAME "
+ "from SUPPLIERS, COFFEES " + "where
SUPPLIERS.SUP_ID = COFFEES.SUP_ID " +
"order by SUP_NAME"
43. • Calling a Stored Procedure from JDBC
CallableStatement cs = con.prepareCall("{call
SHOW_SUPPLIERS}");
44. 5. Executing SQL Statements
String insertString1;
String nama = txtNama.getText();
int age = Integer.parseInt(txtUmur.getText());
String jan = txtJan.getText();
insertString1 = "insert into student values('"+nama+"',
"+age+", '"+jan+"' )";
try {
stmt = con.createStatement();
stmt.executeUpdate(insertString1);
}
• executeUpdate is used for data manipulation: insert,
delete, update, create table, etc. (anything other than
querying!)
45. 6. Process the results (ResultSet)
• A ResultSet provides access to a table of data
generated by executing a Statement.
• Only one ResultSet per Statement can be open at
once.
• The table rows are retrieved in sequence.
• A ResultSet maintains a cursor pointing to its current
row of data.
• The 'next' method moves the cursor to the next row.
– you cannot rewind
46. String selectString;
selectString = "select * from student";
ResultSet rs = stmt.executeQuery(selectString);
while (rs.next()) {
String name = rs.getString("studname");
int age = rs.getInt("studage");
String gender = rs.getString("studgender");
}
• The executeQuery method returns a ResultSet
object representing the query result.
48. Summary
In this presentation you learnt the following
– JDBC is a Java API for executing SQL statements and
supports basic SQL functionality.
– Using JDBC you can send SQL, PL/SQL statements to
almost any relational database.
– There are 4 types of JDBC driver
– JDBC-ODBC bridge , Type 1
– Native-API, Type 2
– JDBC-Net, Type 3
– Native-protocol, Type 4
Notas del editor
relational database is one that presents information in tables with rows and columns.
OCI - (Oracle Call Interface)
The driver is called partly java because the java part of the driver calls the native library. This means that the native library must be at client side i.e. the place where the driver is used.
Database is collection of data in a defined manner.
Database sever is software that helps us to operate on the database
a Database is a collection of related information that may not even involve computers at all. However, the database in the computer sense is stored on a disk and plays the role of an information repository.
A Database server is the process that makes the data in the database available to the outside world
Callable Statement
Execute a call to a database stored procedure
The stored procedure contains the SQL query to be executed on the database and is stored on the database.
A stored procedure is a group of SQL statements that form a logical unit and perform a particular task. Stored procedures are used to encapsulate a set of operations or queries to execute on a database server. For example, operations on an employee database (hire, fire, promote, lookup) could be coded as stored procedures executed by application code. Stored procedures can be compiled and executed with different parameters and results, and they may have any combination of input, output, and input/output parameters
Derby supports all the JDBC 1.2 methods of CallableStatement:getBoolean()
getByte()
getBytes()
getDate()
getDouble()
getFloat()
getInt()
getLong()
getObject()
getShort()
getString()
getTime()
getTimestamp()
registerOutParamter()
wasNull()