0% found this document useful (0 votes)
11 views

Unit 5-Database Connectivity

java database connectivity setp by step expaintion

Uploaded by

khotakash556
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Unit 5-Database Connectivity

java database connectivity setp by step expaintion

Uploaded by

khotakash556
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Unit 5

• Interacting with Database

• 12 MARKS
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 JavaSE (Java Standard Edition).
JDBC API uses JDBC drivers to connect with
the database.
• 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
• The java.sql package contains classes and interfaces
for JDBC API.
Why Should We Use JDBC

• Before JDBC, ODBC API was the database API


to connect and execute the query with the
database.
• But, ODBC API uses ODBC driver which is
written in C language (i.e. platform dependent
and unsecured). That is why Java has defined
its own API (JDBC API) that uses JDBC drivers
(written in Java language).
There are four types of JDBC drivers:
• JDBC-ODBC Bridge Driver,
• Native Driver,
• Network Protocol Driver, and
• Thin Driver
1) JDBC-ODBC bridge 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.
• Note: In Java 8, the JDBC-ODBC Bridge has been removed.
• Advantages
• 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.
• easy to use.
• can be easily connected to any database.
• Disadvantages:
• Performance degraded because JDBC method call is
converted into the ODBC function calls.
• The ODBC driver needs to be installed on the client
machine.
2) Native-API driver

• The Native API driver uses the client-side


libraries of the database. The driver converts
JDBC method calls into native calls of the
database API.
• It is not written entirely in java.
• Advantage:
• performance upgraded than JDBC-ODBC bridge driver.
• Disadvantage:
• The Native driver needs to be installed on the each
client machine.
• The Vendor client library needs to be installed on
client machine.
3) Network Protocol driver
• The Network Protocol driver uses middleware
(application server) that converts JDBC calls
directly or indirectly into the vendor-specific
database protocol. It is fully written in java.
• Advantage:
• No client side library is required because of application
server that can perform many tasks like auditing, load
balancing, logging etc.
• Disadvantages:
• Network support is required on client machine.
• Requires database-specific coding to be done in the middle
tier.
• Maintenance of Network Protocol driver becomes costly
because it requires database-specific coding to be done in
the middle tier.
4) Thin driver

• The thin driver converts JDBC calls directly into


the vendor-specific database protocol. That is
why it is known as thin driver.
• It is fully written in Java language.
• Advantage:
• Better performance than all other drivers.
• No software is required at client side or server
side.
• Disadvantage:
• Drivers depend on the Database.
Java Database Connectivity with 5 Steps
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
• public static void forName(String className)throws
ClassNotFoundException
• Example to register the OracleDriver class
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
1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name
,String password) throws SQLException
• Example to establish connection with the Oracle database
• Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localh
ost:1521:xe","system","password");
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
• public Statement createStatement()throws
SQLException
• Example to create the statement object
• 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
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();
Java Database Connectivity with Oracle

• To connect java application with the oracle database, we need to


follow 5 following steps.
• In this example, we are using Oracle 10g as the database. So we
need to know following information for the oracle database:
• Driver class: The driver class for the oracle database is
oracle.jdbc.driver.OracleDriver.
• 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. You may get all these
information from the tnsnames.ora file.
• Username: The default username for the oracle database is system.
• Password: It is the password given by the user at the time of
installing the oracle database.
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().
Methods of Driver Manager
• public static Connection getConnection(String
URL):It attempts to establish the connection to the
given Database and select an appropriate driver from
the registered drivers. The String parameter has URL,
username, and password to connect with DB.
• public static Connection getConnection(String URL,
String UserName, String Password) It works like
getConnection(String), but here URL, username, and
password given as separate parameters.
• public static Connection getConnection(String
URL, Properties prop):A connection object is
returned by this method after creating a
connection to the database present at the
mentioned URL, which is the first parameter
of this method. The second parameter, which
is "prop", fetches the authentication details of
the database (username and password.)
• pubic static void setLoginTimeout(int sec):t is
used to set the time (seconds) that a driver can
wait till that time while establishing a connection
to connect with DB. If you set LoginTimeout as 0,
then the driver will wait infinitely while
establishing the connection with DB
• public static int getLoginTimeout():It returns the
maximum time (seconds), a driver can wait while
establishing the connection.
• public static synchronized void
registerDriver(Driver driver):It is used to
register the driver to the DriverManager. If the
driver is already registered then it won’t take
any action.
• public static void deregisterDriver(Driver
driver):It is used to remove the specified
driver from the registered list of drivers. If the
driver is not found, it won’t take any action.
• public static Driver getDriver(String URL):It
enables to get a driver object from the
registered drivers of the DriverManager
• public static Enumeration getDrivers(): It
enables to get an array of all the driver object
from the registered drivers of the
DrirverManager
Connection interface

• A Connection is the session between java application


and database.
• The Connection interface is a factory of Statement (i.e
it provides methods to get object of ReseultSet)
• 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.
• Methods
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.
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.
Types of statements used in JDBC:

• Create Statement
• Prepared Statement
• Callable Statement
1. Create a Statement:

• A Statement object is used for general-


purpose access to databases and is useful for
executing static SQL statements at runtime.
• Syntax:
• Statement statement = connection.createStatement();
• Implementation: Once the Statement object is
created, there are three ways to execute it.
• boolean execute(String SQL): If the ResultSet object is
retrieved, then it returns true else false is returned.
• Is used to execute SQL DDL statements or for dynamic
SQL.
• int executeUpdate(String SQL): Returns number of
rows that are affected by the execution of the
statement, used when you need a number for INSERT,
DELETE or UPDATE statements.
• ResultSet executeQuery(String SQL): Returns a
ResultSet object. Used similarly as SELECT is used in
SQL.
• / Importing Database(SQL) classes
• import java.sql.*;
• // Class class GFG
• { // Main driver method
• public static void main(String[] args)
• { // Try block to check if any exceptions occur
• try {
• Class.forName("com.mysql.cj.jdbc.Driver");
• // Registering driver using DriverManager
• Connection con = DriverManager.getConnection( "jdbc:mysql:///world", "root", "12345");
• // Step 3: Create a statement
• Statement statement = con.createStatement();
• String sql = "select * from people";
// Step 4: Execute the query
• ResultSet result = statement.executeQuery(sql);
• while (result.next())
• {
• System.out.println( "Name: " + result.getString("name"));
• System.out.println( "Age:" + result.getString("age")); } }
• catch (SQLException e)
• { // Print the exception
• System.out.println(e);
• }

• catch (ClassNotFoundException e)
• { // Print and display the line number // where exception occurred
2. Prepared Statement:

• A PreparedStatement represents a
precompiled SQL statement that can be
executed multiple times.
• It accepts parameterized SQL queries,
with ? as placeholders for parameters, which
can be set dynamically.
• Considering in the people database if there is a
need to INSERT some values,
• INSERT INTO people VALUES ("Ayan",25);
INSERT INTO people VALUES("Kriya",32);
• To do the same in Java, one may use Prepared
Statements and set the values in the ? holders,
• setXXX() of a prepared statement is used as
shown:
• String query = "INSERT INTO people(name,
age)VALUES(?, ?)";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1,"Ayan");
ptstmt.setInt(2,25);
• Implementation: Once the PreparedStatement object is
created, there are three ways to execute it:
• execute(): This returns a boolean value and executes a
static SQL statement that is present in the prepared
statement object.
• executeQuery(): Returns a ResultSet from the current
prepared statement.
• executeUpdate(): Returns the number of rows affected
by the DML statements such as INSERT, DELETE, and
more that is present in the current Prepared Statement.
3. Callable Statement:
• A CallableStatement is used to execute stored
procedures in the database. Stored procedures
are precompiled SQL statements that can be
called with parameters.
• They are useful for executing complex
operations that involve multiple SQL
statements.
• Syntax: To create a CallableStatement,
• CallableStatement cstmt =
con.prepareCall("{call ProcedureName(?, ?)}");
• {call ProcedureName(?, ?)}: Calls a stored procedure
named ProcedureName with placeholders ? for input
parameters.
• Methods to Execute:
• execute(): Executes the stored procedure and returns
a boolean indicating whether the result is
a ResultSet (true) or an update count (false).
• executeQuery(): Executes a stored procedure that
returns a ResultSet.
• executeUpdate(): Executes a stored procedure that
performs an update and returns the number of rows
affected.

You might also like