SlideShare a Scribd company logo
Java MS Access database connectivity
Follow these steps:
1)Go to the start->Control Panel->Administrative Tools-
> data sources.
2)Click Add button and select the driver Microsoft
Access Driver(*.mdb).
3)After selecting the driver, click finish button.
4)Then give Data Source Name and click ok button.
5)Your DSN will get created.
6) Restart your compiler and compile your java code.
DBC Steps to be followed while writing JDBC
program:
 Loading Driver
 Establishing Connection
 Executing Statements
 Getting Results
 Closing Database Connection
Loading Driver
 Loading Database driver is very first step
towards making JDBC connectivity with the
database. It is necessary to load the JDBC
drivers before attempting to connect to the
database. The JDBC drivers automatically register
themselves with the JDBC system when loaded. Here
is the code for loading the JDBC driver:
Class.forName(driver).newInstance();
Establishing Connection
 In the above step we have loaded the database driver
to be used. Now its time to make the connection with
the database server. In the Establishing Connection
step we will logon to the database with user name
and password. Following code we have used to make
the connection with the database:
con = DriverManager.getConnection(url+db, user, p
ass);
Executing Statements
 In the previous step we established the
connection with the database, now its time to
execute query against database. You can run
any type of query against database to
perform database operations. In this
example we will select all the rows from
employee table. Here is the code that actually
execute the statements against database:
ResultSet rs = st.executeQuery(
"SELECT * FROM Hi" );
Getting Results
 In this step we receives the result of execute
statement. In this case we will fetch the
employees records from the recordset object
and show on the console. Here is the code:
while (rs.next()) {
String Name = res.getInt( " name " );
System.out.println( Name );
}
Closing Database Connection
 Finally it is necessary to disconnect from the
database and release resources being used. If
you don’t close the connection then in the
production environment your application
will fail due to hanging database connections.
Here is the code for disconnecting the
application from database:
con.close();
Ms Access
 import java.sql.*;
 class Search{
 public static void main(String[] args){
 try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
 Connection con =
DriverManager.getConnection("jdbc:odbc:Data");
 Statement st=con.createStatement();
 ResultSet rs=st.executeQuery("select * from
Hi");

 while(rs.next()){
 System.out.println(rs.getString("ID")+"
"+rs.getString("Name"));
 }
 }
 catch(Exception e){
 System.out.println(e);
 }
 }
 }
Insert
 import java.sql.*;
 class JavaApplication1{
 public static void main(String[] args){
 try{
 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
 Connection con =
DriverManager.getConnection("jdbc:odbc:Data");
 Statement st=con.createStatement();
 int ID=5;
 String Name ="Meena";
 int i=st.executeUpdate("insert into Hi(ID,Name) values('"+ ID
+"','"+ Name +"')");
 System.out.println("Row is added"); ResultSet
rs=st.executeQuery("select * from Hi");
 while(rs.next()){
 System.out.println(rs.getString("ID")+"
"+rs.getString("Name"));
 }
 }
 catch(Exception e){
 System.out.println(e);
 }
 }
 }
Update
 import java.sql.*;
 class Update{
 public static void main(String[] args){
 try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
 Connection con =
DriverManager.getConnection("jdbc:odbc:Data");
 Statement st=con.createStatement();

 int i=st.executeUpdate("update Hi set name='Reena' where ID = 3");
 System.out.println("Row is updated");

 ResultSet rs=st.executeQuery("select * from Hi");
 while(rs.next()){
 System.out.println(rs.getString("ID")+" "+rs.getString("Name"));
 }
 }
 catch(Exception e){
 System.out.println(e);
 }
 }
 }
Delete
 import java.sql.*;
 class Delete{
 public static void main(String[] args){
 try{
 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
 Connection con =
DriverManager.getConnection("jdbc:odbc:Data");
 Statement st=con.createStatement();

 int i=st.executeUpdate("delete from Hi where
id=3");
 System.out.println("Row is deleted");
 ResultSet rs=st.executeQuery("select * from Hi");
 while(rs.next()){
 System.out.println(rs.getString("ID")+"
"+rs.getString("Name"));
 }
 }
 catch(Exception e){
 System.out.println(e);
 }
 }
 }
Difference between Statement & PreparedStatement
There are four steps for the execution of query :
• Query is parsed,
•Query is compile,
•Query is optimized and
•Query is executed.
In case of statement interface these four steps are
performed ,each time when query is submitted for execution.
But in case of prepared statement first three steps are
performed only once, when the query in initially submitted. Only
the last step is performed each time query is submitted(in
subsequence submissions),
i.e if same query is submitted to be execute with different
values multiple times then prepared statement interface provides
better perfromance as compared to statement interface.*
•Comparing with the execution control of Statement
–
1) executeXXX() method is invoked on the SQL statement
executeUpdate(), executeQuery()
2) The Statement object submits SQL Statement to DB
3) The DB compiles the given SQL statement
4) An execution plan is prepared by DB to execute the statement
5) Execution plan is then executed.
If SQL contains SELECT, the results are cached in buffer–
Results are sent to the Statement object
6) Finally, response is sent to java application executeUpdate() methods
Normal statement execution
–Compilation includes syntax check, name validation etc.–After
validation, query optimizer prepares execution plan
•Returns best execution plan
•SQL statement goes thru above every time it is executed
•If same query is executed multiple times,
– Then execution plan can be saved and reuse it– This stored
execution plan is known as pre-compiled statement
• The PreparedStatement interface is designed for it –Hence, their
execution is much faster compared to statement
when using PreparedStatement
–Must be associated with one connection
–It represents the execution plan, need to pass parameters
–On connection close, it implicitly gets closed
–Execution of query is processed as follows
The connection object submits the SQL statement todatabase
Database compiles the given statement
•Execution plan is prepared by the database
•Database returns the execution plan with unique id–Connection
object– The setXXX() methods are used to set the parameters of
SQL–
executeXXX () method is invoked to execute the SQL
–Database executes the execution plan with supplied
parameters–Finall the result is sent to the java application
Advantages
–Improves the application performance compared to
Statement()
–Inserts or updates SQL99 data types
•CLOB, BLOB
–Provides a programming approach to set the values
•Disadvantages
–Can represent only one SQL statement at a time
–Can not execute more than one SQL statement in a single
PreparedStatement
•Situations when it is useful to use
–A single query is executed multiple times
–When a query consists of numerous parameters and complex types
Preapre Statement Example
 import java.sql.*;
 public class Prepare {
 static private final String driver =
"sun.jdbc.odbc.JdbcOdbcDriver";
 static private final String connection = "jdbc:odbc:emp";
 public static void main(String args[]) {
 Connection con = null;
 PreparedStatement pst = null;
 ResultSet rs = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(connection);
con.setAutoCommit(false);
String sql =
"insert into Employees (ID,FirstName,LastName)
values(?,?,?)";
pst = con.prepareStatement(sql);
pst.setInt(1,4);
pst.setString(2, "DDD");
pst.setString(3, "JOSHI");
pst.executeUpdate();
pst.close();
sql = "select * from Employees";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
System.out.print(rs.getString(1) + "t");
System.out.print(rs.getString(2) + "t");
System.out.println(rs.getString(3));
}
rs.close();
pst.close();
con.close();
} catch (Exception e) {
}
}
}
Preapre Statement Update Example
 import java.sql.*;
 public class UpdatePre {
 static private final String driver =
"sun.jdbc.odbc.JdbcOdbcDriver";
 static private final String connection = "jdbc:odbc:emp";
 public static void main(String args[]) {
 Connection con = null;
 PreparedStatement pst = null;
 ResultSet rs = null;
 try {
 Class.forName(driver);
 con = DriverManager.getConnection(connection);
 con.setAutoCommit(false);
 String sql = "update Employees set LastName = ? where id =?";
 pst = con.prepareStatement(sql);
 pst.setString(1,"DAVE");
 pst.setInt(2, 2);
 pst.executeUpdate();
 pst.close();
 // System.out.println("updated");
 sql = "select * from Employees";
 pst = con.prepareStatement(sql);
 rs = pst.executeQuery();
 while (rs.next()) {
 System.out.print(rs.getString(1) + "t");
 System.out.print(rs.getString(2) + "t");
 System.out.println(rs.getString(3));
 }

 rs.close();
 pst.close();
 con.close();
 } catch (Exception e) {
 }
 }
 }

JDBC with MySQL
 To connect java application to MySQL database we
must have at least one database created in MySQL.
 And to create database in MySQL, it should be
installed on your system.
 So first of all install MySQL database in your system.
 After installing it open MySQL console.
 Create database with syntax
create database databasename; and press enter.
 You can see message like Query OK, 1 row affected
(0.03 sec)
 Now our database is created in MySQL. Second step
is to create table in our database.
 For creating table in particular database type
Use databasename; and press enter and you can see
message like database changed.
 Now for creating table type create table tablename
(field1 type of field1, field2 type of field2, field3 type
of field3);
 Now press enter again you can see the message like
Query OK, 0 row affected (0.01 sec).
 EX:
 Create database java;
 Use java;
 Create table data (id int,name char(20),city char(20),age
int);
 Now the next step is to insert data into our table.
 For inserting data simply type insert into table name (field1,field2,field3)
values (value1,value2,value3);
 EX:
 insert into data (id,name,city,age) values (1,“ROMA",”AHM",30);
 So by that’s way you can insert as many data as you want in your
table. Now for viewing our data from table just type
 select * from tablename;
 EX:
 select * from data;
 String which we are writing in
Class.forName("com.mysql.jdbc.Driver"); to load the
driver.
 String which we are writing in Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3
306/java","root",”Root") to create connection with
particular database.
 Here the string jdbc:mysql://localhost:3306 is for connecting
MySQL to JDBC in our local system and the name /java is our
database name and 1st "root" is username of MySQL and 2nd
“Root" is password of MySQL.
 Here no need of Data Source Name as in access but
one jar file named mysql-connector-java-5.1.6-
bin.jar must be loded in your java IDE.
 For adding jar file simply right click on your project
and select Set configuration  Customize  library
and you can see window like this.
 Select option add JAR/Folder.
JDBC
 import java.sql.*;
 public class MySqlDemo1
 {
 public static void main(String[] args)
 {
 try
 {
 Class.forName("com.mysql.jdbc.Driver");
 System.out.println("Driver is loaded");
 Connection c =
DriverManager.getConnection("jdbc:mysql://localhost:3306/java",
"root","Root");
 System.out.println("Connection created");

 Statement s = c.createStatement();
 ResultSet rs = s.executeQuery("select * from data");
 System.out.println("IDtNametCitytAge");

 while(rs.next()) // Retrieve data from ResultSet
 {

System.out.println(rs.getString(1)+"t"+rs.getString(2)+"t"+rs.getString(3)+"t"+r
s.getString(4));
 }

 }
 catch(Exception e)
 {
 System.out.println("Exception : " +e);
 }
 }}
Stored procedure in MySql
 Now we all know that for CallableStatement first of all we
must have stored procedure in our database.
 Now how can we create stored procedure in MySQL.
 For that follow the steps given below.
 We already create a database in MySQL now for creating
stored procedure for that particular database
 Use java; (use databasename;)
 Example stored procedure for addition of two numbers.
 DELIMITER $$
CREATE PROCEDURE `addproc`( IN a INT, IN b
INT, OUT c INT)
BEGIN
SET c = a + b;
END$$
 You can get message like Query OK, 0 rows affected
(0.00 sec)
 It means your stored procedure is created successfully.
 Here we create stored procedure for add two int number.
 The stored procedure has 2 IN parameter and 1 OUT
parameter so total 3 parameters
JDBC program for Callable
 mport java.sql.*;
 public class Mysql_CallableDemo
 {
 public static void main(String[] args)
 {
 try
 {
 Class.forName("com.mysql.jdbc.Driver");
 System.out.println("Driver is loaded");
 Connection c =
DriverManager.getConnection("jdbc:mysql://localhost:3306/
java","root","Root");
 System.out.println("Connection created");
 String q = "call addproc(?,?,?)";
 CallableStatement cs = c.prepareCall(q);
 cs.setInt(1, 10);
 cs.setInt(2, 20);
 cs.registerOutParameter(3, Types.INTEGER);
 cs.execute();
 int add = cs.getInt(3);
 System.out.println("addition = "+add);
 }
 catch(Exception e)
 {
 System.out.println("Exception : " +e);
 }
 }
 }
Using finally()
 import java.sql.*;
 public class Mydemo
 {
 public static void main(String[] args) throws SQLException
 {
 Connection c = null;
 try
 {
 Class.forName("com.mysql.jdbc.Driver");
 System.out.println("Driver is loaded");
 c =
DriverManager.getConnection("jdbc:mysql://localhost:3306/java","root","
Root");
 System.out.println("Connection created");
 Statement s = c.createStatement();
 ResultSet rs = s.executeQuery("select * from data");
 System.out.println("IDtNametCitytAge");

 while(rs.next()) // Retrieve data from ResultSet
 {
 System.out.println(rs.getString(1)+"t"+rs.getString(2)+"t"+r
s.getString(3)+"t"+rs.getString(4));
 }

 }
 catch(Exception e)
 {
 System.out.println("Exception : " +e);
 }
 finally
 {
 c.close();
 }
 }}
JDBC Connecticity.ppt

More Related Content

Similar to JDBC Connecticity.ppt

JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
jitendral
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
chhaichivon
 
Jdbc day-1
Jdbc day-1Jdbc day-1
Jdbc day-1
Soham Sengupta
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
BG Java EE Course
 
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
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
Waheedullah Suliman Khail
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
AISHWARIYA1S
 
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 (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
manvibaunthiyal1
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
OUM SAOKOSAL
 
Database connect
Database connectDatabase connect
Database connect
Yoga Raja
 
Jdbc
JdbcJdbc

Similar to JDBC Connecticity.ppt (20)

JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
Jdbc day-1
Jdbc day-1Jdbc day-1
Jdbc day-1
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
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
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
JDBC
JDBCJDBC
JDBC
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
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 (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
22jdbc
22jdbc22jdbc
22jdbc
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Jsp project module
Jsp project moduleJsp project module
Jsp project module
 
Database connect
Database connectDatabase connect
Database connect
 
Jdbc
JdbcJdbc
Jdbc
 

Recently uploaded

一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
top1002
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
ssuser7dcef0
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
symbo111
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
ClaraZara1
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 

Recently uploaded (20)

一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 

JDBC Connecticity.ppt

  • 1. Java MS Access database connectivity Follow these steps: 1)Go to the start->Control Panel->Administrative Tools- > data sources. 2)Click Add button and select the driver Microsoft Access Driver(*.mdb). 3)After selecting the driver, click finish button. 4)Then give Data Source Name and click ok button. 5)Your DSN will get created. 6) Restart your compiler and compile your java code.
  • 2. DBC Steps to be followed while writing JDBC program:  Loading Driver  Establishing Connection  Executing Statements  Getting Results  Closing Database Connection
  • 3. Loading Driver  Loading Database driver is very first step towards making JDBC connectivity with the database. It is necessary to load the JDBC drivers before attempting to connect to the database. The JDBC drivers automatically register themselves with the JDBC system when loaded. Here is the code for loading the JDBC driver: Class.forName(driver).newInstance();
  • 4. Establishing Connection  In the above step we have loaded the database driver to be used. Now its time to make the connection with the database server. In the Establishing Connection step we will logon to the database with user name and password. Following code we have used to make the connection with the database: con = DriverManager.getConnection(url+db, user, p ass);
  • 5. Executing Statements  In the previous step we established the connection with the database, now its time to execute query against database. You can run any type of query against database to perform database operations. In this example we will select all the rows from employee table. Here is the code that actually execute the statements against database: ResultSet rs = st.executeQuery( "SELECT * FROM Hi" );
  • 6. Getting Results  In this step we receives the result of execute statement. In this case we will fetch the employees records from the recordset object and show on the console. Here is the code: while (rs.next()) { String Name = res.getInt( " name " ); System.out.println( Name ); }
  • 7. Closing Database Connection  Finally it is necessary to disconnect from the database and release resources being used. If you don’t close the connection then in the production environment your application will fail due to hanging database connections. Here is the code for disconnecting the application from database: con.close();
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 18.  import java.sql.*;  class Search{  public static void main(String[] args){  try{  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  Connection con = DriverManager.getConnection("jdbc:odbc:Data");  Statement st=con.createStatement();  ResultSet rs=st.executeQuery("select * from Hi"); 
  • 19.  while(rs.next()){  System.out.println(rs.getString("ID")+" "+rs.getString("Name"));  }  }  catch(Exception e){  System.out.println(e);  }  }  }
  • 20.
  • 21.
  • 22. Insert  import java.sql.*;  class JavaApplication1{  public static void main(String[] args){  try{  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  Connection con = DriverManager.getConnection("jdbc:odbc:Data");  Statement st=con.createStatement();  int ID=5;  String Name ="Meena";
  • 23.  int i=st.executeUpdate("insert into Hi(ID,Name) values('"+ ID +"','"+ Name +"')");  System.out.println("Row is added"); ResultSet rs=st.executeQuery("select * from Hi");  while(rs.next()){  System.out.println(rs.getString("ID")+" "+rs.getString("Name"));  }  }  catch(Exception e){  System.out.println(e);  }  }  }
  • 24.
  • 25.
  • 26. Update  import java.sql.*;  class Update{  public static void main(String[] args){  try{  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  Connection con = DriverManager.getConnection("jdbc:odbc:Data");  Statement st=con.createStatement(); 
  • 27.  int i=st.executeUpdate("update Hi set name='Reena' where ID = 3");  System.out.println("Row is updated");   ResultSet rs=st.executeQuery("select * from Hi");  while(rs.next()){  System.out.println(rs.getString("ID")+" "+rs.getString("Name"));  }  }  catch(Exception e){  System.out.println(e);  }  }  }
  • 28.
  • 29.
  • 30. Delete  import java.sql.*;  class Delete{  public static void main(String[] args){  try{  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  Connection con = DriverManager.getConnection("jdbc:odbc:Data");  Statement st=con.createStatement();   int i=st.executeUpdate("delete from Hi where id=3");  System.out.println("Row is deleted");
  • 31.  ResultSet rs=st.executeQuery("select * from Hi");  while(rs.next()){  System.out.println(rs.getString("ID")+" "+rs.getString("Name"));  }  }  catch(Exception e){  System.out.println(e);  }  }  }
  • 32.
  • 33.
  • 34. Difference between Statement & PreparedStatement There are four steps for the execution of query : • Query is parsed, •Query is compile, •Query is optimized and •Query is executed. In case of statement interface these four steps are performed ,each time when query is submitted for execution. But in case of prepared statement first three steps are performed only once, when the query in initially submitted. Only the last step is performed each time query is submitted(in subsequence submissions), i.e if same query is submitted to be execute with different values multiple times then prepared statement interface provides better perfromance as compared to statement interface.*
  • 35. •Comparing with the execution control of Statement – 1) executeXXX() method is invoked on the SQL statement executeUpdate(), executeQuery() 2) The Statement object submits SQL Statement to DB 3) The DB compiles the given SQL statement 4) An execution plan is prepared by DB to execute the statement 5) Execution plan is then executed. If SQL contains SELECT, the results are cached in buffer– Results are sent to the Statement object 6) Finally, response is sent to java application executeUpdate() methods
  • 36.
  • 37. Normal statement execution –Compilation includes syntax check, name validation etc.–After validation, query optimizer prepares execution plan •Returns best execution plan •SQL statement goes thru above every time it is executed •If same query is executed multiple times, – Then execution plan can be saved and reuse it– This stored execution plan is known as pre-compiled statement • The PreparedStatement interface is designed for it –Hence, their execution is much faster compared to statement
  • 38.
  • 39. when using PreparedStatement –Must be associated with one connection –It represents the execution plan, need to pass parameters –On connection close, it implicitly gets closed –Execution of query is processed as follows The connection object submits the SQL statement todatabase Database compiles the given statement •Execution plan is prepared by the database •Database returns the execution plan with unique id–Connection object– The setXXX() methods are used to set the parameters of SQL– executeXXX () method is invoked to execute the SQL –Database executes the execution plan with supplied parameters–Finall the result is sent to the java application
  • 40. Advantages –Improves the application performance compared to Statement() –Inserts or updates SQL99 data types •CLOB, BLOB –Provides a programming approach to set the values •Disadvantages –Can represent only one SQL statement at a time –Can not execute more than one SQL statement in a single PreparedStatement •Situations when it is useful to use –A single query is executed multiple times –When a query consists of numerous parameters and complex types
  • 41. Preapre Statement Example  import java.sql.*;  public class Prepare {  static private final String driver = "sun.jdbc.odbc.JdbcOdbcDriver";  static private final String connection = "jdbc:odbc:emp";  public static void main(String args[]) {  Connection con = null;  PreparedStatement pst = null;  ResultSet rs = null;
  • 42. try { Class.forName(driver); con = DriverManager.getConnection(connection); con.setAutoCommit(false); String sql = "insert into Employees (ID,FirstName,LastName) values(?,?,?)"; pst = con.prepareStatement(sql); pst.setInt(1,4); pst.setString(2, "DDD"); pst.setString(3, "JOSHI");
  • 43. pst.executeUpdate(); pst.close(); sql = "select * from Employees"; pst = con.prepareStatement(sql); rs = pst.executeQuery(); while (rs.next()) { System.out.print(rs.getString(1) + "t"); System.out.print(rs.getString(2) + "t"); System.out.println(rs.getString(3)); }
  • 45.
  • 46. Preapre Statement Update Example  import java.sql.*;  public class UpdatePre {  static private final String driver = "sun.jdbc.odbc.JdbcOdbcDriver";  static private final String connection = "jdbc:odbc:emp";  public static void main(String args[]) {  Connection con = null;  PreparedStatement pst = null;  ResultSet rs = null;
  • 47.  try {  Class.forName(driver);  con = DriverManager.getConnection(connection);  con.setAutoCommit(false);  String sql = "update Employees set LastName = ? where id =?";  pst = con.prepareStatement(sql);  pst.setString(1,"DAVE");  pst.setInt(2, 2);  pst.executeUpdate();  pst.close();  // System.out.println("updated");  sql = "select * from Employees";
  • 48.  pst = con.prepareStatement(sql);  rs = pst.executeQuery();  while (rs.next()) {  System.out.print(rs.getString(1) + "t");  System.out.print(rs.getString(2) + "t");  System.out.println(rs.getString(3));  }   rs.close();  pst.close();  con.close();  } catch (Exception e) {  }  }  } 
  • 49.
  • 50. JDBC with MySQL  To connect java application to MySQL database we must have at least one database created in MySQL.  And to create database in MySQL, it should be installed on your system.  So first of all install MySQL database in your system.  After installing it open MySQL console.
  • 51.
  • 52.  Create database with syntax create database databasename; and press enter.  You can see message like Query OK, 1 row affected (0.03 sec)  Now our database is created in MySQL. Second step is to create table in our database.
  • 53.  For creating table in particular database type Use databasename; and press enter and you can see message like database changed.  Now for creating table type create table tablename (field1 type of field1, field2 type of field2, field3 type of field3);  Now press enter again you can see the message like Query OK, 0 row affected (0.01 sec).
  • 54.  EX:  Create database java;  Use java;  Create table data (id int,name char(20),city char(20),age int);  Now the next step is to insert data into our table.
  • 55.  For inserting data simply type insert into table name (field1,field2,field3) values (value1,value2,value3);  EX:  insert into data (id,name,city,age) values (1,“ROMA",”AHM",30);  So by that’s way you can insert as many data as you want in your table. Now for viewing our data from table just type  select * from tablename;  EX:  select * from data;
  • 56.
  • 57.  String which we are writing in Class.forName("com.mysql.jdbc.Driver"); to load the driver.  String which we are writing in Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3 306/java","root",”Root") to create connection with particular database.  Here the string jdbc:mysql://localhost:3306 is for connecting MySQL to JDBC in our local system and the name /java is our database name and 1st "root" is username of MySQL and 2nd “Root" is password of MySQL.
  • 58.  Here no need of Data Source Name as in access but one jar file named mysql-connector-java-5.1.6- bin.jar must be loded in your java IDE.  For adding jar file simply right click on your project and select Set configuration  Customize  library and you can see window like this.  Select option add JAR/Folder.
  • 59.
  • 60.
  • 61. JDBC  import java.sql.*;  public class MySqlDemo1  {  public static void main(String[] args)  {  try  {  Class.forName("com.mysql.jdbc.Driver");  System.out.println("Driver is loaded");  Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/java", "root","Root");  System.out.println("Connection created"); 
  • 62.  Statement s = c.createStatement();  ResultSet rs = s.executeQuery("select * from data");  System.out.println("IDtNametCitytAge");   while(rs.next()) // Retrieve data from ResultSet  {  System.out.println(rs.getString(1)+"t"+rs.getString(2)+"t"+rs.getString(3)+"t"+r s.getString(4));  }   }  catch(Exception e)  {  System.out.println("Exception : " +e);  }  }}
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68. Stored procedure in MySql  Now we all know that for CallableStatement first of all we must have stored procedure in our database.  Now how can we create stored procedure in MySQL.  For that follow the steps given below.  We already create a database in MySQL now for creating stored procedure for that particular database  Use java; (use databasename;)  Example stored procedure for addition of two numbers.
  • 69.  DELIMITER $$ CREATE PROCEDURE `addproc`( IN a INT, IN b INT, OUT c INT) BEGIN SET c = a + b; END$$
  • 70.
  • 71.  You can get message like Query OK, 0 rows affected (0.00 sec)  It means your stored procedure is created successfully.  Here we create stored procedure for add two int number.  The stored procedure has 2 IN parameter and 1 OUT parameter so total 3 parameters
  • 72. JDBC program for Callable  mport java.sql.*;  public class Mysql_CallableDemo  {  public static void main(String[] args)  {  try  {  Class.forName("com.mysql.jdbc.Driver");  System.out.println("Driver is loaded");  Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/ java","root","Root");  System.out.println("Connection created");
  • 73.  String q = "call addproc(?,?,?)";  CallableStatement cs = c.prepareCall(q);  cs.setInt(1, 10);  cs.setInt(2, 20);  cs.registerOutParameter(3, Types.INTEGER);  cs.execute();  int add = cs.getInt(3);  System.out.println("addition = "+add);  }  catch(Exception e)  {  System.out.println("Exception : " +e);  }  }  }
  • 74.
  • 75. Using finally()  import java.sql.*;  public class Mydemo  {  public static void main(String[] args) throws SQLException  {  Connection c = null;  try  {  Class.forName("com.mysql.jdbc.Driver");  System.out.println("Driver is loaded");  c = DriverManager.getConnection("jdbc:mysql://localhost:3306/java","root"," Root");  System.out.println("Connection created");  Statement s = c.createStatement();
  • 76.  ResultSet rs = s.executeQuery("select * from data");  System.out.println("IDtNametCitytAge");   while(rs.next()) // Retrieve data from ResultSet  {  System.out.println(rs.getString(1)+"t"+rs.getString(2)+"t"+r s.getString(3)+"t"+rs.getString(4));  }   }  catch(Exception e)  {  System.out.println("Exception : " +e);  }  finally  {  c.close();  }  }}