SlideShare ist ein Scribd-Unternehmen logo
1 von 20
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
}
}
}

Weitere ähnliche Inhalte

Was ist angesagt?

Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtapVikas Jagtap
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsFulvio Corno
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database ConnectivityRanjan Kumar
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 
Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course JavaEE Trainers
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technologyvikram singh
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session ManagementFahad Golra
 
Request dispatching in servlet
Request dispatching in servletRequest dispatching in servlet
Request dispatching in servletvikram singh
 

Was ist angesagt? (20)

Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
Servlets
ServletsServlets
Servlets
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Servlets
ServletsServlets
Servlets
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
Request dispatching in servlet
Request dispatching in servletRequest dispatching in servlet
Request dispatching in servlet
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Java server pages
Java server pagesJava server pages
Java server pages
 
Java servlets
Java servletsJava servlets
Java servlets
 

Ähnlich wie Database connect

Ähnlich wie Database connect (20)

JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise Java
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Jdbc
JdbcJdbc
Jdbc
 
Advance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-databaseAdvance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-database
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Core Java Programming Language (JSE) : Chapter XIII -  JDBCCore Java Programming Language (JSE) : Chapter XIII -  JDBC
Core Java Programming Language (JSE) : Chapter XIII - JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
jdbc introduction
jdbc introductionjdbc introduction
jdbc introduction
 
Jdbc tutorial
Jdbc tutorialJdbc tutorial
Jdbc tutorial
 
JDBC
JDBCJDBC
JDBC
 
Unit 5.pdf
Unit 5.pdfUnit 5.pdf
Unit 5.pdf
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
JDBC
JDBCJDBC
JDBC
 
Lecture17
Lecture17Lecture17
Lecture17
 
Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)
 
Jdbc
JdbcJdbc
Jdbc
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 

Mehr von Yoga Raja

Mehr von Yoga Raja (8)

Ajax
AjaxAjax
Ajax
 
Php
PhpPhp
Php
 
Xml
XmlXml
Xml
 
JSON
JSONJSON
JSON
 
Java script
Java scriptJava script
Java script
 
Think-Pair-Share
Think-Pair-ShareThink-Pair-Share
Think-Pair-Share
 
Minute paper
Minute paperMinute paper
Minute paper
 
Decision support system-MIS
Decision support system-MISDecision support system-MIS
Decision support system-MIS
 

Kürzlich hochgeladen

FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoordharasingh5698
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdfEr. Suman Jyoti
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 

Kürzlich hochgeladen (20)

FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 

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>");