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

database connectivity

The document explains how JDBC (Java Database Connectivity) enables Java applications to interact with databases through a structured architecture consisting of the JDBC API and JDBC drivers. It outlines the differences between JDBC and ODBC, details the four types of JDBC drivers, and provides a step-by-step guide for connecting a Java application to a database, including code examples for MySQL. Additionally, it describes the process of executing SQL statements and managing database connections.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

database connectivity

The document explains how JDBC (Java Database Connectivity) enables Java applications to interact with databases through a structured architecture consisting of the JDBC API and JDBC drivers. It outlines the differences between JDBC and ODBC, details the four types of JDBC drivers, and provides a step-by-step guide for connecting a Java application to a database, including code examples for MySQL. Additionally, it describes the process of executing SQL statements and managing database connections.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

How JDBC works

As a developer, you can use JDBC to interact with a database from within a Java program.

JDBC acts as a bridge from your code to the database, as shown in Figure 1.

IDG
Figure 1. JDBC connects Java programs to databases.

JDBC vs ODBC

Before JDBC, developers used Open Database Connectivity (ODBC), a language-agnostic standard
approach to accessing a relational database management system, or RDBMS. In some ways, JDBC
takes its inspiration from ODBC.

The difference is that JDBC is Java-specific, offering a programming-level interface that handles the
mechanics of Java applications communicating with a database.

JDBC’s architecture

The JDBC interface consists of two layers:

1. The JDBC API supports communication between the Java application and the JDBC manager.
2. The JDBC driver supports communication between the JDBC manager and the database driver.

The JDBC API and JDBC driver have been refined extensively over the years, resulting in a feature-
rich, performant, and reliable library.

JDBC is the common API that your application code interacts with. Beneath that is the

JDBC-compliant driver for the database you are using.

Figure 2 illustrates the JDBC architecture.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
IDG

Figure 2. JDBC’s architecture consists of the JDBC API and JDBC drivers.

JDBC Driver is a software component that enables java application to interact with the database.
There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
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.

In Java 8, the JDBC-ODBC Bridge has been removed.

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.

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.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Advantage:

o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

o The Native driver needs to be installed on the each client machine.


o 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.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Advantage:

o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.

Disadvantages:

o Network support is required on client machine.


o Requires database-specific coding to be done in the middle tier.
o 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.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Advantage:

o Better performance than all other drivers.


o No software is required at client side or server side.

Disadvantage:

o Drivers depend on the Database.

What is API

API (Application programming interface) is a document that contains a description of all the
features of a product or software. It represents classes and interfaces that software programs can
follow to communicate with each other. An API can be created for applications, libraries,
operating systems, etc.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Java Database Connectivity with 7 Steps

There are 5 steps to connect any java application with the database using JDBC. These steps are
as follows:
o Import sql package
o Loa driver class
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection

JDBC imports

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.ResultSet;

import java.sql.Statement;

Each of these imports provides access to a class that facilitates the standard Java database
connection:

 Connection represents the connection to the database.

 DriverManager obtains the connection to the database. (Another option is DataSource,


used for connection pooling.)

 SQLException handles SQL errors between the Java application and the database.

 ResultSet and Statement model the data result sets and SQL statements.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
1) Register the driver class

The forName() method of Class class is used to register the driver class. This method is used to dynamically loa
the driver class.

Syntax of forName() method

1. public static void forName(String className)throws ClassNotFoundException

Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's
Jar in the classpath, and then JDBC driver manager can detect and load the driver automatically.

Example to register the OracleDriver class

Here, Java program is loading oracle driver to esteblish database connection.

1. 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. 1) public static Connection getConnection(String url)throws SQLException


2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException

Example to establish connection with the Oracle database

1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object

The createStatement() method of Connection interface is used to create statement. The object of statement
responsible to execute queries with the database.

Syntax of createStatement() method


Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
1. public Statement createStatement()throws SQLException
The statement interface is used to create SQL basic statements in Java it provides methods to
execute queries with the database. There are different types of statements that are used in
JDBC as follows:
 Create Statement
 Prepared Statement
 Callable Statement
1. Create a Statement: From the connection interface, you can create the object for this
interface. It is generally used for general–purpose access to databases and is useful while using
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.

2. Prepared Statement represents a recompiled SQL statement, that can be executed many
times. This accepts parameterized SQL queries. In this, “?” is used instead of the parameter,
one can pass the parameter dynamically by using the methods of PREPARED STATEMENT
at run time.
Illustration:
Considering in the people database if there is a need to INSERT some values, SQL statements
such as these are used:
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(?, ?)";
Statement pstmt = con.prepareStatement(query);
pstmt.setString(1,"Ayan");
ptstmt.setInt(2,25);
// where pstmt is an object name

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
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 are stored procedures which are a group of statements that we compile
in the database for some task, they are beneficial when we are dealing with multiple tables with
complex scenario & rather than sending multiple queries to the database, we can
send the required data to the stored procedure & lower the logic executed in the database
server itself. The Callable Statement interface provided by JDBC API helps in executing stored
procedures.
Syntax: To prepare a CallableStatement

CallableStatement cstmt = con.prepareCall("{call Procedure_name(?, ?}");


Implementation: Once the callable statement object is created
 execute() is used to perform the execution of the statement.

4) Execute the query

The executeQuery() method of Statement interface is used to execute queries to the database. This method return
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

1. ResultSet rs=stmt.executeQuery("select * from emp");


2.
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
The close() method of Connection interface is used to close the connection.

Syntax of close() method

1. public void close()throws SQLException

Example to close connection

1. con.close();

Note: Since Java 7, JDBC has ability to use try-with-resources statement to automatically close
resources of type Connection, ResultSet, and Statement.

Java Database Connectivity with MySQL

To connect Java application with the MySQL database, we need to follow 5 following steps.

In this example we are using MySql as the database. So we need to know following informations
for the mysql database:

1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/bank where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address, 3306
is the port number and bank is the database name. We may use any database, in such
case, we need to replace the sonoo with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.

Let's first create a table in the mysql database, but before creating table, we need to create
database first.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
package db;

import java.sql.*;

import java.util.*;

public class mysql {

public static void main(String[] args) throws Exception{

// TODO Auto-generated method stub

Scanner sc = new Scanner(System.in);

System.out.println("enter username and password");

String un = sc.nextLine();

String pw = sc.nextLine();

Class.forName("com.mysql.jdbc.Driver");

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/bank?characterEncoding=latin1",
"root", "Sai@12345");

/*Statement st = con.createStatement();

//ResultSet rs = st.executeQuery("select * from student");

while(rs.next()) {

System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getFloat(3));

}*/

PreparedStatement pspt = con.prepareStatement("select * from


Login where username=? and psw=?");

pspt.setString(1, un);

pspt.setString(2, pw);

ResultSet rs1 = pspt.executeQuery();

if(rs1.next()) {

System.out.println(rs1.getString(1) + "login success");

else {

System.out.println("wrong details");

con.close();

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT

You might also like