SlideShare a Scribd company logo
2
Most read
5
Most read
10
Most read
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
}
}
}

More Related Content

PPTX
JSP- JAVA SERVER PAGES
PPTX
Java Servlet
PDF
JAVA EE DEVELOPMENT (JSP and Servlets)
PPS
Jdbc example program with access and MySql
PPS
Jdbc api
PPTX
JSP - Java Server Page
PPT
Jsp sasidhar
PPT
Data Access with JDBC
JSP- JAVA SERVER PAGES
Java Servlet
JAVA EE DEVELOPMENT (JSP and Servlets)
Jdbc example program with access and MySql
Jdbc api
JSP - Java Server Page
Jsp sasidhar
Data Access with JDBC

What's hot (20)

PPT
Java Server Pages
PPTX
Jsp presentation
PPT
Servlet ppt by vikas jagtap
PDF
Introduction to JDBC and database access in web applications
PPTX
PPT
JDBC Java Database Connectivity
PPT
Java servlet life cycle - methods ppt
PPT
JAVA Servlets
PPT
JDBC – Java Database Connectivity
PPTX
java Servlet technology
PPT
Introduction to the Servlet / JSP course
PPS
JSP Error handling
PPT
An Introduction To Java Web Technology
PPTX
Servlets
DOC
Java Servlets & JSP
PDF
Lecture 3: Servlets - Session Management
PPT
Request dispatching in servlet
PPT
Jdbc ppt
PPSX
Java server pages
PPTX
Java servlets
Java Server Pages
Jsp presentation
Servlet ppt by vikas jagtap
Introduction to JDBC and database access in web applications
JDBC Java Database Connectivity
Java servlet life cycle - methods ppt
JAVA Servlets
JDBC – Java Database Connectivity
java Servlet technology
Introduction to the Servlet / JSP course
JSP Error handling
An Introduction To Java Web Technology
Servlets
Java Servlets & JSP
Lecture 3: Servlets - Session Management
Request dispatching in servlet
Jdbc ppt
Java server pages
Java servlets
Ad

Similar to Database connect (20)

PDF
PPTX
Java- JDBC- Mazenet Solution
PPTX
Core jdbc basics
PPTX
PDF
Core Java Programming Language (JSE) : Chapter XIII - JDBC
PPTX
Jdbc ppt
PDF
Unit 5.pdf
PPTX
Jdbc presentation
PDF
JDBC Presentation with JAVA code Examples.pdf
PPT
Jdbc connectivity
PPTX
Advance Java Programming (CM5I)5.Interacting with-database
PPT
jdbc_presentation.ppt
PPTX
JDBC PPT(4).pptx java Database Connectivity
PPT
JDBC.ppt
PPT
Basic Java Database Connectivity(JDBC)
PPT
Java database connectivity
PPT
Java database connectivity
PPTX
Java Data Base Connectivity concepts.pptx
PDF
Jdbc[1]
Java- JDBC- Mazenet Solution
Core jdbc basics
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Jdbc ppt
Unit 5.pdf
Jdbc presentation
JDBC Presentation with JAVA code Examples.pdf
Jdbc connectivity
Advance Java Programming (CM5I)5.Interacting with-database
jdbc_presentation.ppt
JDBC PPT(4).pptx java Database Connectivity
JDBC.ppt
Basic Java Database Connectivity(JDBC)
Java database connectivity
Java database connectivity
Java Data Base Connectivity concepts.pptx
Jdbc[1]
Ad

More from Yoga Raja (8)

PPTX
Ajax
PPTX
PPTX
PPTX
JSON
PDF
Java script
DOCX
Think-Pair-Share
DOCX
Minute paper
PPTX
Decision support system-MIS
Ajax
JSON
Java script
Think-Pair-Share
Minute paper
Decision support system-MIS

Recently uploaded (20)

PPTX
Construction Project Organization Group 2.pptx
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
Well-logging-methods_new................
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
Welding lecture in detail for understanding
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PPTX
Lecture Notes Electrical Wiring System Components
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
Internet of Things (IOT) - A guide to understanding
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
Structs to JSON How Go Powers REST APIs.pdf
Construction Project Organization Group 2.pptx
Arduino robotics embedded978-1-4302-3184-4.pdf
OOP with Java - Java Introduction (Basics)
CYBER-CRIMES AND SECURITY A guide to understanding
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
Well-logging-methods_new................
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Operating System & Kernel Study Guide-1 - converted.pdf
Welding lecture in detail for understanding
Lesson 3_Tessellation.pptx finite Mathematics
Lecture Notes Electrical Wiring System Components
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Foundation to blockchain - A guide to Blockchain Tech
Internet of Things (IOT) - A guide to understanding
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Structs to JSON How Go Powers REST APIs.pdf

Database connect

  • 1. Database Connectivity Prepared By Yogaraja C A Ramco Institute of Technology
  • 2. 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.
  • 3. 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)
  • 4. Java Database Connectivity with 5 Steps Register the driver class Creating connection Creating statement Executing queries Closing connection
  • 5. 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");
  • 6. 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);
  • 7. 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();
  • 8. 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)); }
  • 9. 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();
  • 10. 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().
  • 11. 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.
  • 12. 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.
  • 13. 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.
  • 14. 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.
  • 15. 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.
  • 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{ 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);} }}
  • 18. 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";
  • 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>");