Java Database Connectivity With 5 Steps
Java Database Connectivity With 5 Steps
There are 5 steps to connect any java application with the database using JDBC.
1. public static void forName(String className)throws ClassNotFoundExcepti
on
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.
1. Class.forName("oracle.jdbc.driver.OracleDriver");
1. 1) public static Connection getConnection(String url)throws SQLException
2. 2) public static Connection getConnection(String url,String name,String pass
word)
3. throws SQLException
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
1. public Statement createStatement()throws SQLException
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.
1. public ResultSet executeQuery(String sql)throws SQLException
1. ResultSet rs=stmt.executeQuery("select * from emp");
2.
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }
1. public void close()throws SQLException
1. con.close();
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:
Create a Table
Before establishing connection, let's first create a table in oracle database.
Following is the SQL query to create a table.
1. create table emp(id number(10),name varchar2(40),age number(3));
In this example, we are connecting to an Oracle database and getting data from
emp table. Here, system and oracle are the username and password of the Oracle
database.
1. import java.sql.*;
2. class OracleCon{
3. public static void main(String args[]){
4. try{
5. //step1 load the driver class
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. //step2 create the connection object
8. Connection con=DriverManager.getConnection(
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10.//step3 create the statement object
11.Statement stmt=con.createStatement();
12.//step4 execute query
13.ResultSet rs=stmt.executeQuery("select * from emp");
14.while(rs.next())
15.System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
16.//step5 close the connection object
17.con.close();
18.}catch(Exception e){ System.out.println(e);} } }
2) set classpath:
There are two ways to set the classpath:
temporary
permanent
1) Statement
Statement interface is used to execute normal SQL queries. You can’t pass the
parameters to SQL query at run time using this interface. This interface is preferred
over other two interfaces if you are executing a particular SQL query only once.
The performance of this interface is also very less compared to other two
interfaces. In most of time, Statement interface is used for DDL statements like
CREATE, ALTER, DROP etc. For example, ?
2) PreparedStatement
//Executing PreparedStatement
pstmt.executeUpdate();
2) PreparedStatement
//Executing PreparedStatement
pstmt.executeUpdate();
3) CallableStatement
cstmt.execute();
//Use cstmt.getter() methods to retrieve the result returned by the stored procedure
It is used to execute
It is used to execute normal
parameterized or dynamic It is used to call the stored procedures.
SQL queries.
SQL queries.
First step in establishing the connection with any database is registering the JDBC
driver class of that database with DriverManager. As we are using Oracle database
in our examples, we register ‘oracle.jdbc.driver.OracleDriver‘ class, which is the
JDBC driver class of the Oracle, with the DriverManager. As this step has to be
performed only once for the whole execution, it is better to keep this step in Static
Initialization Block. Don’t forget to update your classpath with JDBC driver of the
Oracle database. Otherwise you will get ClassNotFoundException at run time.
n the fourth step, we send the queries to the database. While sending we use
following methods of Satement object depending upon the type of queries we are
sending to the database.
In the last step, we close all the DB resources – Connection, Statement and
ResultSet objects.
{
static
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch (ClassNotFoundException e)
{
}
}
{
try
{
//Database Credentials
stmt = con.createStatement();
"DISIGNATION VARCHAR2(200))";
int i = stmt.executeUpdate(sql);
if(i == 0)
{
System.out.println("Table is created");
}
else
{
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
try
{
if(stmt!=null)
{
stmt.close();
stmt=null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
try
{
if(con!=null)
{
con.close();
con=null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
static
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch (ClassNotFoundException e)
{
}
}
{
try
{
//Database Credentials
stmt = con.createStatement();
int i = stmt.executeUpdate(sql);
if(i != 0)
{
System.out.println("Row is created");
}
else
{
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
//STEP 5 : Closing The DB Resources
try
{
if(stmt!=null)
{
stmt.close();
stmt=null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
try
{
if(con!=null)
{
con.close();
con=null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
static
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch (ClassNotFoundException e)
{
System.out.println("Unable To Load The Driver class");
}
}
{
ResultSet rs = null;
try
{
//Database Credentials
stmt = con.createStatement();
while (rs.next())
{
System.out.println("ID :"+rs.getInt(1));
System.out.println("Designation :"+rs.getString(4));
System.out.println("-------------------");
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
try
{
if(rs!=null)
{
rs.close();
rs=null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
try
{
if(stmt!=null)
{
stmt.close();
stmt=null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
try
{
if(con!=null)
{
con.close();
con=null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
static
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver"); }
try {
//Database Credentials
stmt = con.createStatement();
int i = stmt.executeUpdate(sql);
if(i != 0) {
System.out.println("Record is updated"); }
else {
e.printStackTrace(); }
finally {
try {
if(stmt!=null) {
stmt.close();
stmt=null; } }
e.printStackTrace(); }
try {
if(con!=null) {
con.close();
con=null; } }
e.printStackTrace(); } } }}
static {
try {
Class.forName("oracle.jdbc.driver.OracleDriver"); }
try {
//Database Credentials
stmt = con.createStatement();
int i = stmt.executeUpdate(sql);
if(i != 0) {
System.out.println("Record is deleted"); }
else {
e.printStackTrace(); }
finally {
try {
if(stmt!=null) {
stmt.close();
stmt=null; } }
e.printStackTrace(); }
try {
if(con!=null) {
con.close();
con=null; } }
e.printStackTrace(); } } }}
n this post, we will discuss in detail about which method to use for which SQL
statements and how executeQuery(), executeUpdate() and execute() methods
differ from each other. It is also one of the tricky java interview question. So it is
better to know the differences between these methods before attending an
interview.
This method is used for SQL statements which retrieve some data from the
database. For example is SELECT statement. This method is meant to be used for
select queries which fetch some data from the database. This method returns
one java.sql.ResultSet object which contains the data returned by the query.
This method is used for SQL statements which update the database in some way.
For example INSERT, UPDATE and DELETE statements. All these statements
are DML(Data Manipulation Language) statements. This method can also be used
for DDL(Data Definition Language) statements which return nothing. For example
CREATE and ALTER statements. This method returns an int value which
represents the number of rows affected by the query. This value will be 0 for the
statements which return nothing.
This method can be used for all types of SQL statements. If you don’t know which
method to use for you SQL statements, then this method can be the best option.
This method returns a boolean value. TRUE indicates that statement has returned
a ResultSet object and FALSE indicates that statement has returned an int value or
returned nothing.
Create a Table
Before establishing connection, let's first create a table in oracle database.
Following is the SQL query to create a table.
1. create table emp(id number(10),name varchar2(40),age number(3));
In this example, we are connecting to an Oracle database and getting data from
emp table. Here, system and oracle are the username and password of the Oracle
database.
1. import java.sql.*;
2. class OracleCon{
3. public static void main(String args[]){
4. try{
5. //step1 load the driver class
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. //step2 create the connection object
8. Connection con=DriverManager.getConnection(
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10.//step3 create the statement object
11.Statement stmt=con.createStatement();
12.//step4 execute query
13.ResultSet rs=stmt.executeQuery("select * from emp");
14.while(rs.next())
15.System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
16.//step5 close the connection object
17.con.close();
18.}catch(Exception e){ System.out.println(e);} } }