Database Connectivity
Prepared By
Yogaraja C A
Ramco Institute of Technology
Introduction
 Java JDBC is a Java API to connect and execute query
with the database. JDBC API uses jdbc drivers to
connect with the database.
 We can use JDBC API to access tabular data stored into
any relational database.
JDBC Driver
JDBC Driver is a software component that enables
java application to interact with the database. There
are 4 types of JDBC drivers:
 TYPE-1: JDBC-ODBC bridge driver
 TYPE-2: Native-API driver (partially java driver)
 TYPE-3: Network Protocol driver (fully java
driver)
 TYPE-4: Thin driver (fully java driver)
Java Database Connectivity with 5 Steps
Register the driver class
Creating connection
Creating statement
Executing queries
Closing connection
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.
to register the OracleDriver class
 Class.forName("oracle.jdbc.driver.OracleDriver");
to register the SQL class
 Class.forName("com.mysql.jdbc.Driver");
to register the MSACCESS class
 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Create the connection object
The getConnection() method of DriverManager class is
used to establish connection with the database.
Syntax
 public static Connection getConnection(String url,String n
ame,String password) throws SQLException
Example
 Connection conn =
DriverManager.getConnection(DB_URL, USERNAME,
PASSWORD);
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();
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)); }
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();
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 DriverManager class
Method Description
public static void
registerDriver(Driver driver):
is used to register the given driver
with DriverManager.
public static void
deregisterDriver(Driver driver):
is used to deregister the given driver
(drop the driver from the list) with
DriverManager.
public static Connection
getConnection(String url):
is used to establish the connection
with the specified url.
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.
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.
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.
Example-MYSQL
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/DB","root",“pwd");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1));
con.close(); }
catch(Exception e)
{ System.out.println(e);} } }
Example-MSACCESS
import java.sql.*;
class Test{
public static void main(String ar[]){
try{
String url="jdbc:odbc:mydsn";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from login");
while(rs.next()){
System.out.println(rs.getString(1));
}
}catch(Exception ee){System.out.println(ee);}
}}
Example
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class DatabaseAccess extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/TEST";
static final String USER = "root";
static final String PASS = "password";
Example
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>n" + "<body >n" );
try {
Register JDBC driver Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
String sql;
sql = “INSERT into Employees(1,’Bala’,’Murugan’,22)";
stmt.executeQuery(sql);
out.println( "<h1>“+Inserted Successfully +”</h1>”);
out.println("</body></html>");
Example
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
//Handle errors
}
}
}

Database connect

  • 1.
    Database Connectivity Prepared By YogarajaC A Ramco Institute of Technology
  • 2.
    Introduction  Java JDBCis a Java API to connect and execute query with the database. JDBC API uses jdbc drivers to connect with the database.  We can use JDBC API to access tabular data stored into any relational database.
  • 3.
    JDBC Driver JDBC Driveris a software component that enables java application to interact with the database. There are 4 types of JDBC drivers:  TYPE-1: JDBC-ODBC bridge driver  TYPE-2: Native-API driver (partially java driver)  TYPE-3: Network Protocol driver (fully java driver)  TYPE-4: Thin driver (fully java driver)
  • 4.
    Java Database Connectivitywith 5 Steps Register the driver class Creating connection Creating statement Executing queries Closing connection
  • 5.
    Register the driverclass The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class. to register the OracleDriver class  Class.forName("oracle.jdbc.driver.OracleDriver"); to register the SQL class  Class.forName("com.mysql.jdbc.Driver"); to register the MSACCESS class  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  • 6.
    Create the connectionobject The getConnection() method of DriverManager class is used to establish connection with the database. Syntax  public static Connection getConnection(String url,String n ame,String password) throws SQLException Example  Connection conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
  • 7.
    Create the Statementobject 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();
  • 8.
    Execute the query TheexecuteQuery() 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)); }
  • 9.
    Close the connectionobject 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();
  • 10.
    DriverManager class The DriverManagerclass 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().
  • 11.
    Methods of DriverManagerclass Method Description public static void registerDriver(Driver driver): is used to register the given driver with DriverManager. public static void deregisterDriver(Driver driver): is used to deregister the given driver (drop the driver from the list) with DriverManager. public static Connection getConnection(String url): is used to establish the connection with the specified url. public static Connection getConnection(String url,String userName,String password): is used to establish the connection with the specified url, username and password.
  • 12.
    Connection interface A Connectionis 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.
  • 13.
    Methods of Connectioninterface: 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.
  • 14.
    Statement interface The Statementinterface 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.
  • 15.
    Methods of Statementinterface: 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.
  • 16.
    Example-MYSQL 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/DB","root",“pwd"); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select * from emp"); while(rs.next()) System.out.println(rs.getInt(1)); con.close(); } catch(Exception e) { System.out.println(e);} } }
  • 17.
    Example-MSACCESS import java.sql.*; class Test{ publicstatic void main(String ar[]){ try{ String url="jdbc:odbc:mydsn"; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c=DriverManager.getConnection(url); Statement st=c.createStatement(); ResultSet rs=st.executeQuery("select * from login"); while(rs.next()){ System.out.println(rs.getString(1)); } }catch(Exception ee){System.out.println(ee);} }}
  • 18.
    Example import java.io.*; import java.util.*; importjavax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class DatabaseAccess extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL="jdbc:mysql://localhost/TEST"; static final String USER = "root"; static final String PASS = "password";
  • 19.
    Example response.setContentType("text/html"); PrintWriter out =response.getWriter(); out.println("<html>n" + "<body >n" ); try { Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); String sql; sql = “INSERT into Employees(1,’Bala’,’Murugan’,22)"; stmt.executeQuery(sql); out.println( "<h1>“+Inserted Successfully +”</h1>”); out.println("</body></html>");
  • 20.