SlideShare a Scribd company logo
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

What's hot

Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
BG Java EE Course
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
Sher Singh Bardhan
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
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
Fulvio Corno
 
Servlets
ServletsServlets
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
Ranjan Kumar
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
kamal kotecha
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
deepak kumar
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
Tanmoy 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
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
kamal kotecha
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
vikram singh
 
Servlets
ServletsServlets
Servlets
Geethu Mohan
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
Manjunatha RK
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
Fahad Golra
 
Request dispatching in servlet
Request dispatching in servletRequest dispatching in servlet
Request dispatching in servlet
vikram singh
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
Vikas Jagtap
 
Java server pages
Java server pagesJava server pages
Java server pages
Tanmoy Barman
 
Java servlets
Java servletsJava servlets
Java servlets
yuvarani p
 

What's hot (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
 

Similar to Database connect

JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
Hitesh-Java
 
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
PawanMM
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
Fulvio Corno
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
Fulvio Corno
 
Jdbc
JdbcJdbc
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
Payal Dungarwal
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
Arati Gadgil
 
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
WebStackAcademy
 
Jdbc
JdbcJdbc
Jdbc
JdbcJdbc
Jdbc
lathasiva
 
jdbc introduction
jdbc introductionjdbc introduction
jdbc introduction
Rashmi Dhanotiya
 
Jdbc tutorial
Jdbc tutorialJdbc tutorial
Jdbc tutorial
Dharma Kshetri
 
JDBC
JDBCJDBC
Unit 5.pdf
Unit 5.pdfUnit 5.pdf
Unit 5.pdf
saturo3011
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
Information Technology
 
JDBC
JDBCJDBC
Lecture17
Lecture17Lecture17
Lecture17
vantinhkhuc
 
Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)
Luzan Baral
 
Java JDBC
Java JDBCJava JDBC
Jdbc
JdbcJdbc

Similar to 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)
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Jdbc
JdbcJdbc
Jdbc
 

More from Yoga Raja

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

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

Recently uploaded

LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
Anant Corporation
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
ydzowc
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
UReason
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
gowrishankartb2005
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
bjmsejournal
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
Nada Hikmah
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
ecqow
 
Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
bijceesjournal
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
Data Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptxData Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptx
ramrag33
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
ElakkiaU
 
integral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdfintegral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdf
gaafergoudaay7aga
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
Mahmoud Morsy
 

Recently uploaded (20)

LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
 
Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
Data Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptxData Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptx
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
 
integral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdfintegral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdf
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
 

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