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

JDBC

Java JDBC is an API for connecting and executing queries with databases, using JDBC drivers written in Java. It provides a structured approach to database connectivity through five main steps: registering the driver, creating a connection, creating a statement, executing a query, and closing the connection. The document also outlines the roles of various interfaces such as DriverManager, Connection, Statement, ResultSet, and PreparedStatement in managing database interactions.

Uploaded by

bale061699
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)
19 views

JDBC

Java JDBC is an API for connecting and executing queries with databases, using JDBC drivers written in Java. It provides a structured approach to database connectivity through five main steps: registering the driver, creating a connection, creating a statement, executing a query, and closing the connection. The document also outlines the roles of various interfaces such as DriverManager, Connection, Statement, ResultSet, and PreparedStatement in managing database interactions.

Uploaded by

bale061699
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/ 11

Java JDBC

Java JDBC is a java API to connect and execute query with the database. JDBC API
uses jdbc drivers to connect with the database.

Why use JDBC

Before JDBC, ODBC API was the database API to connect and execute 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).

What is API

API (Application programming interface) is a document that contains 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
5 Steps to connect to the database in java

• Register the driver class


• Create the connection object
• Create the Statement object
• Execute the query
• Close the connection object

There are 5 steps to connect any java application with the database in java using
JDBC. They are as follows:

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

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

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

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 connect to the mysql database in java

For connecting java application with the mysql database, you need to follow 5
steps to perform database connectivity.

In this example we are using MySql as the database. So we need to know


following informations for the mysql database:

Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
Connection URL: The connection URL for the mysql database is
jdbc:mysql://localhost:3306/sonoo 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 sonoo is the database name. We may use
any database, in such case, you need to replace the sonoo with your database
name.
Username: The default username for the mysql database is root.
Password: Password is 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.

create database sonoo;


use sonoo;
create table emp(id int(10),name varchar(40),age int(3));

Example to Connect Java Application with mysql database

In this example, sonoo is the database name, root is the username and password.

import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
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().

Useful methods of DriverManager class

1) public static void registerDriver(Driver driver): is used to register the given driver
with DriverManager.

2) public static void deregisterDriver(Driver driver): is used to deregister the


given driver (drop the driver from the list) with DriverManager.

3) public static Connection getConnection(String url): is used to establish the


connection with the specified url.

4) public static Connection getConnection(String url,String userName,String


password): is used to establish the connection with the specified url, username and
password.

Connection interface

A Connection is the session between java application and database. The Connection
interface is a factory of Statement, 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. By default,
connection commits the changes after executing queries.

Commonly used methods of Connection interface:

1) public Statement createStatement(): creates a statement object that can be


used to execute SQL queries.

2) public Statement createStatement(int resultSetType,int resultSetConcurrency):


Creates a Statement object that will generate ResultSet objects with the given type
and concurrency.

3) public void setAutoCommit(boolean status): is used to set the commit status.By


default it is true.

4) public void commit(): saves the changes made since the previous
commit/rollback permanent.

5) public void rollback(): Drops all changes made since the previous
commit/rollback.

6) public void close(): closes the connection and Releases a JDBC resources
immediately.

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.
Commonly used methods of Statement interface:

1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It


returns the object of ResultSet.

2) public int executeUpdate(String sql): is used to execute specified query, it may


be create, drop, insert, update, delete etc.

3) public boolean execute(String sql): is used to execute queries that may return
multiple results.

4) public int[] executeBatch(): is used to execute batch of commands.

ResultSet interface

The object of ResultSet maintains a cursor pointing to a row of a table. Initially,


cursor points to before the first row. By default, ResultSet object can be moved
forward only and it is not updatable.

Commonly used methods of ResultSet interface

1) public boolean next(): is used to move the cursor to the one row next from the
current position.

2) public boolean previous(): is used to move the cursor to the one row
previous from the current position.

3) public boolean first(): is used to move the cursor to the first row in result set
object.
4) public boolean last(): is used to move the cursor to the last row in result set
object.

5) public boolean absolute(int row): is used to move the cursor to the specified
row number in the ResultSet object.

6) public boolean relative(int row): is used to move the cursor to the relative
row number in the ResultSet object, it may be positive or negative.

7) public int getInt(int columnIndex): is used to return the data of specified


column index of the current row as int.

8) public int getInt(String columnName): is used to return the data of specified


column name of the current row as int.

9) public String getString(int columnIndex): is used to return the data of specified


column index of the current row as String.

10) public String getString(String columnName): is used to return the data of


specified column name of the current row as String.

PreparedStatement interface

The PreparedStatement interface is a subinterface of Statement. It is used to


execute parameterized query.

Let's see the example of parameterized query:

String sql="insert into emp values(?,?,?)";


As you can see, we are passing parameter (?) for the values. Its value will be set
by calling the setter methods of PreparedStatement.

Why use PreparedStatement?

Improves performance: The performance of the application will be faster if you


use PreparedStatement interface because query is compiled only once.

Methods of PreparedStatement interface

public void setInt(int paramIndex, int value) sets the integer value to the given
parameter index.
public void setString(int paramIndex, String value) sets the String value to the
given parameter index.
public void setFloat(int paramIndex, float value) sets the float value to the given
parameter index.
public void setDouble(int paramIndex, double value) sets the double value to
the given parameter index.
public int executeUpdate() executes the query. It is used for create, drop,
insert, update, delete etc.
public ResultSet executeQuery() executes the select query. It returns an
instance of ResultSet.

You might also like