SlideShare una empresa de Scribd logo
1 de 48
JAVA DATABASE
CONNECTIVITY (JDBC)
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
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
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
JDBC Interfaces
JDBC Class
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
• 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
JDBC Driver
• 4 types of JDBC drivers:
JDBC-ODBC bridge (Type 1)
Native-API, partly Java driver (Type 2)
JDBC-Net, pure Java driver (Type 3)
Native-protocol, pure Java driver (Type 4)
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)
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.
Configure Driver
– ODBC use Microsoft Product for database
which is Microsoft Access.
– Go to the Administrative Tools in Control
Panel.
15
16
• 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
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.
• 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
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.
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
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
Load and Register the JDBC driver:
Class.forName("com.jw.client.JWDriver");
RMI – Remote Method Invocation
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.
Disadvantages
• It requires another server application to install and
maintain.
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
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
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.
A List of JDBC Driver Vendors
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
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
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
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.
2. Define the connection
• import java.sql.Connection;
• Connection con;
– connect to a database
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
4. Create JDBC statement(s)
• Statement stmt = con.createStatement() ;
• Creates a Statement object for sending SQL statements
to the database
JDBC Statements
• Statement
• Prepared Statement
• Callable Statement
Statement
– Execute simple sql queries without parameters
• Statement stmt = con.createStatement();
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’")
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"
• Calling a Stored Procedure from JDBC
CallableStatement cs = con.prepareCall("{call
SHOW_SUPPLIERS}");
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!)
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
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.
7. Close connection
• stmt.close();
• con.close();
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

Más contenido relacionado

La actualidad más candente

Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
Maher Abdo
 

La actualidad más candente (20)

Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
 
jdbc document
jdbc documentjdbc document
jdbc document
 
Database and Java Database Connectivity
Database and Java Database ConnectivityDatabase and Java Database Connectivity
Database and Java Database Connectivity
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Jdbc
JdbcJdbc
Jdbc
 
Overview Of JDBC
Overview Of JDBCOverview Of JDBC
Overview Of JDBC
 
Java Database Connectivity (Advanced programming)
Java Database Connectivity (Advanced programming)Java Database Connectivity (Advanced programming)
Java Database Connectivity (Advanced programming)
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
Jdbc_ravi_2016
Jdbc_ravi_2016Jdbc_ravi_2016
Jdbc_ravi_2016
 
JDBC Architecture and Drivers
JDBC Architecture and DriversJDBC Architecture and Drivers
JDBC Architecture and Drivers
 
java database connection (jdbc)
java database connection (jdbc)java database connection (jdbc)
java database connection (jdbc)
 
Jdbcdriver
JdbcdriverJdbcdriver
Jdbcdriver
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
JDBC
JDBCJDBC
JDBC
 
JDBC Connectivity Model
JDBC Connectivity ModelJDBC Connectivity Model
JDBC Connectivity Model
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 

Similar a Chap3 3 12

JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.ppt
kingkolju
 

Similar a Chap3 3 12 (20)

4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
 
java.pptx
java.pptxjava.pptx
java.pptx
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.ppt
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
jdbc
jdbcjdbc
jdbc
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Unit 5.pdf
Unit 5.pdfUnit 5.pdf
Unit 5.pdf
 
Jdbc
JdbcJdbc
Jdbc
 
Mobile Application Devlopement-Database connections-UNIT-5
Mobile Application Devlopement-Database connections-UNIT-5Mobile Application Devlopement-Database connections-UNIT-5
Mobile Application Devlopement-Database connections-UNIT-5
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
java database connectivity for java programming
java database connectivity for java programmingjava database connectivity for java programming
java database connectivity for java programming
 
JDBC
JDBCJDBC
JDBC
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
Unit 5-jdbc2
Unit 5-jdbc2Unit 5-jdbc2
Unit 5-jdbc2
 
jdbc
jdbcjdbc
jdbc
 
Jdbc
JdbcJdbc
Jdbc
 

Más de Hemo Chella (15)

Chap4 4 2
Chap4 4 2Chap4 4 2
Chap4 4 2
 
Chap4 4 1
Chap4 4 1Chap4 4 1
Chap4 4 1
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Chap1 1 4
Chap1 1 4Chap1 1 4
Chap1 1 4
 
Chap1 1 1
Chap1 1 1Chap1 1 1
Chap1 1 1
 
Chap1 1.4
Chap1 1.4Chap1 1.4
Chap1 1.4
 
Chap1 1.1
Chap1 1.1Chap1 1.1
Chap1 1.1
 
Fp601 chapter 6
Fp601   chapter 6Fp601   chapter 6
Fp601 chapter 6
 
Fp601 chapter 5 -part 1
Fp601   chapter 5 -part 1Fp601   chapter 5 -part 1
Fp601 chapter 5 -part 1
 
Fp601 chapter 5 - part 2
Fp601   chapter 5 - part 2Fp601   chapter 5 - part 2
Fp601 chapter 5 - part 2
 
Fp601 chapter 4
Fp601   chapter 4Fp601   chapter 4
Fp601 chapter 4
 
Fp601 chapter 3 - part 2
Fp601   chapter 3 - part 2Fp601   chapter 3 - part 2
Fp601 chapter 3 - part 2
 
Fp601 chapter 3 - part 1
Fp601   chapter 3 - part 1Fp601   chapter 3 - part 1
Fp601 chapter 3 - part 1
 
Fp601 chapter 2
Fp601   chapter 2Fp601   chapter 2
Fp601 chapter 2
 
Fp601 chapter 1
Fp601   chapter 1Fp601   chapter 1
Fp601 chapter 1
 

Último

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 

Último (20)

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 

Chap3 3 12

  • 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
  • 9. JDBC Driver • 4 types of JDBC drivers: JDBC-ODBC bridge (Type 1) Native-API, partly Java driver (Type 2) JDBC-Net, pure Java driver (Type 3) Native-protocol, pure Java driver (Type 4)
  • 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.
  • 13.
  • 14.
  • 15. 15
  • 16. 16
  • 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.
  • 27. Disadvantages • It requires another server application to install and maintain.
  • 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.
  • 31. A List of JDBC Driver Vendors
  • 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
  • 39. JDBC Statements • Statement • Prepared Statement • Callable Statement
  • 40. Statement – Execute simple sql queries without parameters • Statement stmt = con.createStatement();
  • 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.
  • 47. 7. Close connection • stmt.close(); • con.close();
  • 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

  1. relational database is one that presents information in tables with rows and columns.
  2. 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. 
  3. 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
  4. 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()