SlideShare a Scribd company logo
JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to
connect and execute the query with the database. It is a part of Java SE
(Java Standard Edition). JDBC API uses JDBC drivers to connect with
the database. The JDBC library includes APIs for each of the tasks
mentioned below that are commonly associated with database usage.
• Making a connection to a database.
• Creating SQL or MySQL statements.
• Executing SQL or MySQL queries in the database.
• Viewing & Modifying the resulting records.
Applications of JDBC
Fundamentally, JDBC is a specification that provides a complete set of
interfaces that allows for portable access to an underlying database.
Java can be used to write different types of executables, such as −
• Java Applications
• Java Applets
• Java Servlets
• Java ServerPages (JSPs)
• Enterprise JavaBeans (EJBs).
All of these different executable are able to use a JDBC driver to access
a database, and take advantage of the stored data.
We can use JDBC API to access tabular data stored in any
relational database. By the help of JDBC API, we can save, update,
delete and fetch data from the database. It is like Open Database
Connectivity (ODBC) provided by Microsoft.
The current version of JDBC is 4.3. It is the stable release since 21st
September, 2017. It is based on the X/Open SQL Call Level Interface.
The java.sql package contains classes and interfaces for JDBC API. A
list of popular interfaces of JDBC API are given below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface
A list of popular classes of JDBC API is given below:
o DriverManager class
o Types class
There are four types of JDBC drivers:
o JDBC-ODBC Bridge Driver,
o Native Driver,
o Network Protocol Driver, and
o Thin Driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function
calls.
This is now discouraged because of thin driver.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle
recommends that you use JDBC drivers provided by the vendor of your
database instead of the JDBC-ODBC Bridge.
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into
the ODBC function calls.
o The ODBC driver needs to be installed on the client machine.
Topic: Establishing Connectivity
There are 5 steps to connect any java application with the database using
JDBC. These steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
1) Register the driver class
The forName() method of Class class is used to register the driver class.
This method is used to dynamically load the driver class.
Syntax of forName() method
1. public static void forName(String className)throws ClassNotFoundE
xception
Example to register the OracleDriver class
Here, Java program is loading oracle driver to establish database connection.
Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
The getConnection() method of DriverManager class is used to establish
Connection with the database.
Syntax of getConnection() method
public static Connection getConnection(String url)throws SQLExceptio
n
public static Connection getConnection(String url,String username,String p
assword) throws
SQLException
Example to establish connection with the Oracle
database
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:
1521:xe","system","system");
1. Driver class: The driver class for the oracle database
is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database,
thin is the driver, localhost is the server name on which oracle is running, we may also
use IP address, 1521 is the port number and XE is the Oracle service name.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle
database.
3) Create the Statement object
The createStatement() method of Connection Interface is used to create statement.
The object of statement is responsible to execute queries with the database.
Syntax of createStatement() method
1. public Statement createStatement() throws SQLException
Example to create the statement object
1. Statement stmt=con.createStatement();
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries
to the database.This method returns the object of ResultSet that can be
used to get all the records of a table.
Syntax of executeQuery() method
1. public ResultSet executeQuery(String sql) throws SQLException
Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5) Close the connection object
By closing connection object statement and ResultSet will be closed automatically
The close() method of Connection interface is used to close the connection.
Syntax of close() method
public void close() throws SQLException
Example to close connection
con.close();
Creating and Executing SQL statement
Executing SQL on the Connection involves two further objects:
• we create a Statement object, to which we pass the SQL to be
executed and set any required options;
• we read the result of the query via a ResultSet object.
Creating a Statement object is simple once we have our Connection:
Connection con =DriverManager.getConnection();
Statement stmt = con.createStatement();
Then, to execute a simple SQL statement and get the corresponding
result, we write something as follows:
int id = ... get ID from somewhere ...
String sql = "SELECT Name FROM Users WHERE Id = " + id;
ResultSet rs = st.executeQuery(sql);
// ... read from result set ...
The executeQuery() method returns a ResultSet object from
which the result data can be read. For a simple SELECT query
such as this, we would always expect a result set to be returned,
which would be empty if no rows were returned.
The ResultSet object returned can then be queried to pull out the
rows and colums of the result.
Working With ResultSet Object
Having obtained a database connection and executed a query via
a Statement object, the next stage is to pull out the data from the ResultSet. A
result set consists of zero or more rows. Let's suppose that our query on
a User’s table returns rows in the following format:
Id
(INT)
UserName
(VARCHAR)
FirstName
(VARCHAR)
Surname
(VARCHAR)
TimeRegistered
(TIMESTAMP)
3 dsmith David Smith 2008-04-02 18:16:22
4 ntroberts Nigel Roberts 2008-05-01 20:11:01
6 bgsmithers Bill Smithers 2008-05-02 02:43:52
Now we can pull out the details of successive users from the result as follows:
ResultSet rs = st.getResultSet();
try {
while (rs.next()) {
int id = rs.getInt(1);
String userName = rs.getString(2);
String firstName = rs.getString(3);
String surname = rs.getString(4);
Timestamp timeReg = rs.getTimestamp(5);
// ... do something with these variables ...
}
}
finally {
con.close();
}
Notice the repeated call to next(), which returns true if there is another row of
data, and at the same time gets the ResultSet ready to start reading data from
that next row.
The code above illustrates the following points and topics:
• Column numbers start at 1, not zero.
• There are mappings between SQL and Java data types. For example, a
SQL INT is mapped to a Java int; SQL VARCHARs are mapped to
Java Strings. We call a get() method on the ResultSet that is appropriate to
the type we want to retrieve. (As discussed on the next page, it turns out that
these methods luckily can often perform conversion if we don't choose the
exact type.)
• The ResultSet and/or Statement needs to be closed. Whilst in emergencies
they will be closed on finalization, it's preferable to close them explicitly as
soon as they are no longer needed. Unfortunately, there are three different
types of JDBC resource, all of which have a close() method! In a moment,
we'll discuss when to close JDBC resources.
Jdbc
Jdbc

More Related Content

What's hot

What's hot (19)

Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
Database programming
Database programmingDatabase programming
Database programming
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC
JDBCJDBC
JDBC
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
 
JDBC
JDBCJDBC
JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc connectivity in java
Jdbc connectivity in javaJdbc connectivity in java
Jdbc connectivity in java
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
 
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Core Java Programming Language (JSE) : Chapter XIII -  JDBCCore Java Programming Language (JSE) : Chapter XIII -  JDBC
Core Java Programming Language (JSE) : Chapter XIII - JDBC
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
Jdbc   Jdbc
Jdbc
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
 
Sql interview-book
Sql interview-bookSql interview-book
Sql interview-book
 
Database connect
Database connectDatabase connect
Database connect
 

Similar to Jdbc (20)

JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
JDBC
JDBCJDBC
JDBC
 
Prashanthi
PrashanthiPrashanthi
Prashanthi
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
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
 
Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)
 
Lecture17
Lecture17Lecture17
Lecture17
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
Final Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.pptFinal Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.ppt
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
Advance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-databaseAdvance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-database
 

Recently uploaded

To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsPaul Groth
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsVlad Stirbu
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀DianaGray10
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...Product School
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Product School
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesThousandEyes
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Alison B. Lowndes
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Thierry Lestable
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backElena Simperl
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxDavid Michel
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...Product School
 

Recently uploaded (20)

To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 

Jdbc

  • 1. JDBC JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the database. It is a part of Java SE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the database. The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database usage. • Making a connection to a database. • Creating SQL or MySQL statements. • Executing SQL or MySQL queries in the database. • Viewing & Modifying the resulting records. Applications of JDBC Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable access to an underlying database. Java can be used to write different types of executables, such as − • Java Applications • Java Applets • Java Servlets • Java ServerPages (JSPs) • Enterprise JavaBeans (EJBs). All of these different executable are able to use a JDBC driver to access a database, and take advantage of the stored data. We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC API, we can save, update, delete and fetch data from the database. It is like Open Database Connectivity (ODBC) provided by Microsoft.
  • 2. The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based on the X/Open SQL Call Level Interface. The java.sql package contains classes and interfaces for JDBC API. A list of popular interfaces of JDBC API are given below: o Driver interface o Connection interface o Statement interface o PreparedStatement interface o CallableStatement interface o ResultSet interface o ResultSetMetaData interface o DatabaseMetaData interface o RowSet interface A list of popular classes of JDBC API is given below: o DriverManager class o Types class There are four types of JDBC drivers: o JDBC-ODBC Bridge Driver, o Native Driver,
  • 3. o Network Protocol Driver, and o Thin Driver The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin driver.
  • 4. Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge. Advantages: o easy to use. o can be easily connected to any database. Disadvantages: o Performance degraded because JDBC method call is converted into the ODBC function calls. o The ODBC driver needs to be installed on the client machine.
  • 5. Topic: Establishing Connectivity There are 5 steps to connect any java application with the database using JDBC. These steps are as follows: o Register the Driver class o Create connection o Create statement o Execute queries o Close connection 1) Register the driver class The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.
  • 6. Syntax of forName() method 1. public static void forName(String className)throws ClassNotFoundE xception Example to register the OracleDriver class Here, Java program is loading oracle driver to establish database connection. Class.forName("oracle.jdbc.driver.OracleDriver"); 2) Create the connection object The getConnection() method of DriverManager class is used to establish Connection with the database. Syntax of getConnection() method public static Connection getConnection(String url)throws SQLExceptio n public static Connection getConnection(String url,String username,String p assword) throws SQLException Example to establish connection with the Oracle database Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost: 1521:xe","system","system"); 1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver. 2. Connection URL: The connection URL for the oracle10G database is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin is the driver, localhost is the server name on which oracle is running, we may also use IP address, 1521 is the port number and XE is the Oracle service name. 3. Username: The default username for the oracle database is system.
  • 7. 4. Password: It is the password given by the user at the time of installing the oracle database. 3) Create the Statement object The createStatement() method of Connection Interface is used to create statement. The object of statement is responsible to execute queries with the database. Syntax of createStatement() method 1. public Statement createStatement() throws SQLException Example to create the statement object 1. Statement stmt=con.createStatement(); 4) Execute the query The executeQuery() method of Statement interface is used to execute queries to the database.This method returns the object of ResultSet that can be used to get all the records of a table. Syntax of executeQuery() method 1. public ResultSet executeQuery(String sql) throws SQLException Example to execute query ResultSet rs=stmt.executeQuery("select * from emp"); while(rs.next()) { System.out.println(rs.getInt(1)+" "+rs.getString(2)); }
  • 8. 5) Close the connection object By closing connection object statement and ResultSet will be closed automatically The close() method of Connection interface is used to close the connection. Syntax of close() method public void close() throws SQLException Example to close connection con.close();
  • 9. Creating and Executing SQL statement Executing SQL on the Connection involves two further objects: • we create a Statement object, to which we pass the SQL to be executed and set any required options; • we read the result of the query via a ResultSet object. Creating a Statement object is simple once we have our Connection: Connection con =DriverManager.getConnection(); Statement stmt = con.createStatement(); Then, to execute a simple SQL statement and get the corresponding result, we write something as follows: int id = ... get ID from somewhere ... String sql = "SELECT Name FROM Users WHERE Id = " + id; ResultSet rs = st.executeQuery(sql); // ... read from result set ... The executeQuery() method returns a ResultSet object from which the result data can be read. For a simple SELECT query such as this, we would always expect a result set to be returned, which would be empty if no rows were returned. The ResultSet object returned can then be queried to pull out the rows and colums of the result.
  • 10. Working With ResultSet Object Having obtained a database connection and executed a query via a Statement object, the next stage is to pull out the data from the ResultSet. A result set consists of zero or more rows. Let's suppose that our query on a User’s table returns rows in the following format: Id (INT) UserName (VARCHAR) FirstName (VARCHAR) Surname (VARCHAR) TimeRegistered (TIMESTAMP) 3 dsmith David Smith 2008-04-02 18:16:22 4 ntroberts Nigel Roberts 2008-05-01 20:11:01 6 bgsmithers Bill Smithers 2008-05-02 02:43:52 Now we can pull out the details of successive users from the result as follows: ResultSet rs = st.getResultSet(); try { while (rs.next()) { int id = rs.getInt(1); String userName = rs.getString(2); String firstName = rs.getString(3); String surname = rs.getString(4); Timestamp timeReg = rs.getTimestamp(5); // ... do something with these variables ... } } finally { con.close(); } Notice the repeated call to next(), which returns true if there is another row of data, and at the same time gets the ResultSet ready to start reading data from that next row. The code above illustrates the following points and topics: • Column numbers start at 1, not zero.
  • 11. • There are mappings between SQL and Java data types. For example, a SQL INT is mapped to a Java int; SQL VARCHARs are mapped to Java Strings. We call a get() method on the ResultSet that is appropriate to the type we want to retrieve. (As discussed on the next page, it turns out that these methods luckily can often perform conversion if we don't choose the exact type.) • The ResultSet and/or Statement needs to be closed. Whilst in emergencies they will be closed on finalization, it's preferable to close them explicitly as soon as they are no longer needed. Unfortunately, there are three different types of JDBC resource, all of which have a close() method! In a moment, we'll discuss when to close JDBC resources.