SlideShare a Scribd company logo
1 of 56
Database Connectivity in Java
DATABASE BASED APPLICATION
 Database is used to store data. It is also known as
persistent storage as the data is stored and can be
retrieved anytime. 2
INTRODUCTION
 Database
 Collection of data
 DBMS
 Database management system
 Storing and organizing data
 SQL
 Relational database
 Structured Query Language
 CRUD operation in SQL
stands for create, read, update, delete.
INTRODUCTION
 Relational database
 Table
 Record
 Field, column
 Primary key
Unique data
 SQL statement
 Query
 Record sets
SIMPLE DATABASE APPLICATION
A
P
P
L
I
C
A
T
I
O
N
DBMS DB
Ex: Access
Oracle
Sybase
MULTI-DATABASES
A
P
P
L
I
C
A
T
I
O
N
DBMS 1
DBMS 2
DBMS 3
DB
DB
DB
STANDARD ACCESS TO DB
A
P
P
L
I
C
A
T
I
O
N
D
R
I
V
E
R
M
G
R
DBMS
Driver 1
DBMS
Driver 2
DBMS
Driver 3
DBMS 1
DBMS 2
DBMS 3
DB
DB
DB
OPEN DATABASE CONNECTIVITY
(ODBC) STANDARD
ODBC standard is an interface by which application
programs can access and process SQL databases in a
DBMS-independent manner. It contains:
A Data Source that is the database, its associated
DBMS, operating system and network platform
A DBMS Driver that is supplied by the DBMS vendor or
independent software companies
A Driver Manager that is supplied by the vendor of the
O/S platform where the application is running
ODBC ARCHITECTURE
Application
Class1 Class2
Driver Manager
DriverType1 DriverType2 DriverType3
DataSource2
DataSource1 DataSource3
ODBC
ODBC INTERFACE
 It is a system independent interface to database
environment that requires an ODBC driver to be
provided for each database system from which
you want to manipulate data.
 The database driver bridges the differences
between your underlying system calls and the
ODBC interface functionality.
AN EXAMPLE
Application DriverManager
Sybase driver mSQL driver Informix driver
APPLICATION IN JAVA
Application in
Java
DriverManager
Sybase driver mSQL driver Informix driver
JAVA SUPPORT FOR ODBC : JDBC
 When applications written in Java want to
access data sources, they use classes and
associated methods provided by Java DBC
(JDBC) API.
 JDBC is specified as an “interface”.
 An interface in Java can have many
“implementations”.
 So it provides a convenient way to realize
many “drivers”
 JDBC uses drivers to translate generalized JDBC
calls into vendor-specific database calls
 Drivers exist for most popular databases
 Four Classes of JDBC drivers exist
Type I
Type II
Type III
Type IV
JDBC
Drivers
 Type I driver provides mapping between JDBC and access API of a database
 The access API calls the native API of the database to establish communication
 A common Type I driver defines a JDBC to ODBC bridge
 ODBC is the database connectivity for databases
 JDBC driver translates JDBC calls to corresponding ODBC calls
 Thus if ODBC driver exists for a database this bridge can be used to
communicate with the database from a Java application
 Inefficient and narrow solution
 Inefficient, because it goes through multiple layers
 Narrow, since functionality of JDBC code limited to whatever ODBC supports
JDBC
Drivers (Type I)
Client
Application
ODBC
API
Database
Driver
(Type
I)
Native
API Database Specific
Protocol
API Protocol
 Type II driver communicates directly with native API
 Type II makes calls directly to the native API calls
 More efficient since there is one less layer to contend with
(i.e. no ODBC)
 It is dependent on the existence of a native API for a
database
JDBC
Drivers (Type II)
Client
Application Database
Driver
(Type
II)
Native
API
Database Specific
Protocol
API Protocol
 Type III driver make calls to a middleware component running on
another server
 This communication uses a database independent net protocol
 Middleware server then makes calls to the database using database-
specific protocol
 The program sends JDBC call through the JDBC driver to the middle
tier
 Middle-tier may use Type I or II JDBC driver to communicate with the
database.
JDBC
Drivers (Type III)
Database
Client
Application
Driver
(Type
III)
Middleware
Server
Net Protocol Database Specific
Protocol
 Type IV driver is an all-Java driver that is also called a thin
driver
 It issues requests directly to the database using its native protocol
 It can be used directly on platform with a JVM
 Most efficient since requests only go through one layer
 Simplest to deploy since no additional libraries or middle-ware
JDBC
Drivers (Type IV)
Database
Client
Application
Driver
(Type
IV)
Database Specific
Protocol
JDBC ARCHITECTURE (CONT.)
Application JDBC Driver
 Java code calls JDBC library
 JDBC loads a driver
 Driver talks to a particular database
 An application can work with several databases by using all
corresponding drivers
JAVA SUPPORT FOR SQL
 Java supports embedded SQL.
 Also it provides an JDBC API as a standard way
to connect to common relational databases.
 Java.sql package and an extensive exception
hierarchy.
DATA SOURCE AND DRIVER
 Data source is the data base created using any
of the common database applications available.
 Your system should have the driver for the
database you will be using.
 For example your Windows system should have
the MS Access Driver.
 There are a number of JDBC drivers available.
 Information on installing them is available at :
http://industry.java.sun.com/products/jdbc/drivers
JDBC COMPONENTS
 Driver Manager: Loads database drivers, and manages
the connection between application & driver.
 Driver: Translates API calls to operations for a specific
data source.
 Connection: A session between an application and a
driver.
 Statement: A SQL statement to perform a query or an
update operation.
 Metadata: Information about the returned data, driver
and the database.
 Result Set : Logical set of columns and rows returned by
executing a statement.
JDBC CLASSES
 Java supports DB facilities by providing classes and
interfaces for its components
 DriverManager class
 Connection interface
 Statement interface (to be instantiated with values from
the actual SQL statement)
 ResultSet interface
JDBC PROGRAMMING STEPS
1. Import necessary packages; Ex: import java.sql.*;
2. Load JDBC driver(driver should have been installed)
3. Data source and its location should have been
registered.
4. Allocate Connection object, Statement or
PreparedStatement object and ResultSet object
5. Execute query using Statement or
PreparedStatement object
6. Retrieve data from ResultSet object
7. Close Connection object.
BASIC SELECT QUERY
 Simplest format of a SELECT query
 SELECT * FROM tableName
 SELECT * FROM authors
 Select specific fields from a table
 SELECT authorID, lastName FROM authors
authorID lastName
1 Deitel
2 Deitel
3 Nieto
4 Santry
Fig. 8.13 authorID and lastName from the authors table.
WHERE CLAUSE
 specify the selection criteria
 SELECT fieldName1, fieldName2, … FROM tableName WHERE
criteria
 SELECT title, editionNumber, copyright
FROM titles
WHERE copyright > 1999
 WHERE clause condition operators
 <, >, <=, >=, =, <>
INSERT INTO STATEMENT
 Insert a new record into a table
 INSERT INTO tableName ( fieldName1, … ,
fieldNameN )
VALUES ( value1, … , valueN )
 INSERT INTO authors ( firstName, lastName )
VALUES ( ‘Sue’, ‘Smith’ )
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
3 Tem Nieto
4 Sean Santry
5 Sue Smith
Fig. 8.22 T
able Authors after an INSERT INTO operation to add a rec ord.
UPDATE STATEMENT
 Modify data in a table
 UPDATE tableName
SET fieldName1 = value1, … , fieldNameN =
valueN
WHERE criteria
 UPDATE authors
SET lastName = ‘Jones’
WHERE lastName = ‘Smith’ AND firstName
= ‘Sue’
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
3 Tem Nieto
4 Sean Santry
5 Sue Jones
Fig. 8.23 T
able authors after an UPDATE operation to c hange a rec ord.
DELETE FROM STATEMENT
 Remove data from a table
 DELETE FROM tableName WHERE criteria
 DELETE FROM authors
WHERE lastName = ‘Jones’ AND
firstName = ‘Sue’
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
3 Tem Nieto
4 Sean Santry
Fig. 8.24 T
able authors after a DELETE operation to remove a rec ord.
JDBC PROGRAMMING STEPS
31
32
STEP 1: LOAD THE DRIVER
 Loading drivers – An appropriate driver must be loaded
using the statement shown below before connecting to
a databases
33
STEP 2:DEFINE THE CONNECTION URL
 To connect to a database, use the static method
getConnection(databaseURL) :
e.g. Connection conn1 = DriverManager.getConnection
(databaseURL);
34
EXAMPLE 1
public static final String DB_NAME ="registration.db";
public static final String CONNECTION_STRING = "jdbc:
sqlite: D:databases"+DB_NAME;
Connection conn1 =
DriverManager.getConnection(CONNECTION_STRIN
G);
35
EXAMPLE 2
36
STEP 3: ESTABLISH THE CONNECTION
 The following statement creates a Connection
object:
Connection conn1;
conn1 = DriverManager.getConnection(url);
37
STEP 4: CRATING STATEMENT OR PREPARED
STATEMENT
 Statement and PreparedStatement interface defines the
methods and properties that enable you to send SQL
commands and receive data from your database.
 Once a Connection object is created, you can create
statements for executing SQL statements as follows:
Statement st = conn1.createStatement();
PreparedStatement ps= conn1.prepareStatement();
38
METHODS OF STATEMENT INTERFACE
 boolean execute (String SQL): Returns a boolean value of true if
a ResultSet object can be retrieved; otherwise, it returns false.
 Use this method to execute SQL DDL statements
 int executeUpdate (String SQL): Returns the number of rows
affected by the execution of the SQL statement.
 Use this method to execute SQL statements for which you expect
to get a number of rows affected.
- for example, an INSERT, UPDATE, or DELETE statement.
 ResultSet executeQuery (String SQL): Returns a ResultSet
object. Use this method when you expect to get a result set, as
you would with a SELECT statement.
39
STEP 5: EXECUTE A QUERY USING THE
STATEMENT
An SQL query statement can be executed using
String queryCheck = "SELECT * from login";
rs = st.executeQuery(queryCheck);
 An SQL update statement can be executed using
executeUpdate(String sql),
 Example:
st.executeUpdate("INSERT INTO authors ( firstName,
lastName ) VALUES ( 'Sue', 'Smith' )" );
40
RESULTSET
 The SELECT statement is the standard way to
select rows from a database and view them in a
result set.
 The java.sql.ResultSet interface represents the
result set of a database query.
 A ResultSet object maintains a cursor that points to
the current row in the result set.
 The term "result set" refers to the row and column
data contained in a ResultSet object.

41
RESULTSET
 ResultSet objects provide access to the tables generated as
results of executing a Statement queries
 Only one ResultSet per Statement can be open at the same
time!
 The table rows are retrieved in sequence
 A ResultSet maintains a cursor pointing to its current row
 The next() method moves the cursor to the next row
RESULTSET METHODS
 boolean next()
 activates the next row
 the first call to next() activates the first row
 returns false if there are no more rows
 Type getType(int columnIndex)
 returns the given field as the given type
 indices start at 1 and not 0
 Type getType(String columnName)
 same, but uses name of field
 int findColumn(String columnName)
 looks up column index given column name
STEP 6: PROCESSING RESULT
 The result of the query is returned in ResultSet,
Example:
 ResultSet rs = st.executeQuery(queryCheck);
Eg:
rs = st.executeQuery(queryCheck);
while(rs.next()){
s=rs.getString("login_name");
System.out.println("login= "+s);
p=rs.getString("password");
System.out.println("password= "+p);
}
44
EXAMPLE
45
ABOUT PREPARED STATEMENTS
 Extends functionality of Statement interface
 Gives the flexibility of supplying arguments dynamically.
 They are parsed (compiled) by the DBMS only once
 Column values can be set after compilation
 Instead of values, use ‘?’
 The setXXX() methods bind values to the parameters,
where XXX represents the Java data type of the value
you wish to bind to the input parameter.
STEP 5: EXECUTE A QUERY USING THE
PREPAREDSTATEMENT
 Can execute query using execute(), executeQuery()
and executeUpdate()
 Example:
ps.executeUpdate("update customer set acctype=?
where cname=?" );
47
EXAMPLE
48
49
STEP 7:CLEANING UP AFTER YOURSELF
 Remember to close the Connections, Statements, Prepared
Statements and Result Sets
con.close();
stmt.close();
rs.close()
SELECT QUERY
ID fname lname
1 John Smith
2 Paul Dietel
3 Tem Neito
50
ResultSet rs= st.executeQuery(“SELECT *FROM employee”);
while(rs.next()){
int id= rs.getInt(1);
String f_name = rs.getString(“fname”);
String l_name = rs. getString(“lname”);
}
Table: employee
SELECT QUERY
ID fname lname
1 John Smith
2 Paul Dietel
3 Tem Neito
51
String selectquery = “SELECT *FROM employee WHERE
lname=?”;
PreparedStatement ps = con.prepareStatement(selectquery) ;
ps.setSting(1, “Smith”);
ResultSet rs= ps.executeQuery();
while(rs.next()){
int id= rs.getInt(1);
String f_name = rs.getString(“fname”);
String l_name = rs. getString(“lname”);
}
INSERT QUERY
int id=122;
String f_name=“John”;
String l_name= “Mathew”;
String INSERT_QUERY = "INSERT INTO employee (ID,
fname, lname) VALUES (?, ?, ?)";
PreparedStatement ps =
con.prepareStatement(INSERT_QUERY) ;
ps.setInt(1, id);
ps.setString(2, f_name);
ps.setString(3, l_name);
ps.executeUpdate();
52
UPDATE QUERY
String updatequery = “UPDATE employee SET lname = ? fname
= ? WHERE ID= ?” ;
PreparedStatement ps = con.prepareStatement(updatequery);
ps.setString(1, “Allamaraju”);
ps.setString(2, “M”);
ps.setInt(3, 123);
ps.executeUpdate();
53
DELETE QUERY
String deleteQuery = "DELETE FROM employee WHERE
fname = ?";
PreparedStatement ps =
con.prepareStatement(deleteQuery);
ps.setString(1,”John”);
int result = ps.executeUpdate();
System.out.println(result + “Row deleted”);
54
MAPPING JAVA TYPES TO SQL TYPES
SQL type Java Type
CHAR, VARCHAR, LONGVARCHAR String
NUMERIC, DECIMAL java.math.BigDecimal
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT, DOUBLE double
BINARY, VARBINARY, LONGVARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
SUMMARY
 JDBC allows you to write Java programs that
manipulate a database
 A driver (often a separate product) is required that
facilitates access
 Key classes: Connection, Statement,
PreparedStatement, and ResultSet
Thank You
57

More Related Content

Similar to Final Database Connectivity in JAVA.ppt

Similar to Final Database Connectivity in JAVA.ppt (20)

Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Prashanthi
PrashanthiPrashanthi
Prashanthi
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
 
Unit 5-jdbc2
Unit 5-jdbc2Unit 5-jdbc2
Unit 5-jdbc2
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
java 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptxjava 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptx
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
jdbc
jdbcjdbc
jdbc
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
 
Jdbc new
Jdbc newJdbc new
Jdbc new
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC
JDBCJDBC
JDBC
 
3 jdbc
3 jdbc3 jdbc
3 jdbc
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
JDBC
JDBCJDBC
JDBC
 

More from TabassumMaktum

Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptTabassumMaktum
 
Session 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .pptSession 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .pptTabassumMaktum
 
Session 6_Java Interfaces_Details_Programs.pdf
Session 6_Java Interfaces_Details_Programs.pdfSession 6_Java Interfaces_Details_Programs.pdf
Session 6_Java Interfaces_Details_Programs.pdfTabassumMaktum
 
Introduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologiesIntroduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologiesTabassumMaktum
 
531AlmadhorAlwageed2010.ppt
531AlmadhorAlwageed2010.ppt531AlmadhorAlwageed2010.ppt
531AlmadhorAlwageed2010.pptTabassumMaktum
 
Introduction to Lex.ppt
Introduction to Lex.pptIntroduction to Lex.ppt
Introduction to Lex.pptTabassumMaktum
 
GUI design using JAVAFX.ppt
GUI design using JAVAFX.pptGUI design using JAVAFX.ppt
GUI design using JAVAFX.pptTabassumMaktum
 
The World of Web Development 2015 - Part2.pptx
The World of Web Development 2015 - Part2.pptxThe World of Web Development 2015 - Part2.pptx
The World of Web Development 2015 - Part2.pptxTabassumMaktum
 

More from TabassumMaktum (15)

Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
 
Session 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .pptSession 6_Interfaces in va examples .ppt
Session 6_Interfaces in va examples .ppt
 
Session 6_Java Interfaces_Details_Programs.pdf
Session 6_Java Interfaces_Details_Programs.pdfSession 6_Java Interfaces_Details_Programs.pdf
Session 6_Java Interfaces_Details_Programs.pdf
 
Introduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologiesIntroduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologies
 
DigiLocker-Intro.pptx
DigiLocker-Intro.pptxDigiLocker-Intro.pptx
DigiLocker-Intro.pptx
 
Chapter12.ppt
Chapter12.pptChapter12.ppt
Chapter12.ppt
 
ch13.ppt
ch13.pptch13.ppt
ch13.ppt
 
531AlmadhorAlwageed2010.ppt
531AlmadhorAlwageed2010.ppt531AlmadhorAlwageed2010.ppt
531AlmadhorAlwageed2010.ppt
 
Ch3.ppt
Ch3.pptCh3.ppt
Ch3.ppt
 
Introduction to Lex.ppt
Introduction to Lex.pptIntroduction to Lex.ppt
Introduction to Lex.ppt
 
lex.pptx
lex.pptxlex.pptx
lex.pptx
 
Cloud Computing.pptx
Cloud Computing.pptxCloud Computing.pptx
Cloud Computing.pptx
 
GUI design using JAVAFX.ppt
GUI design using JAVAFX.pptGUI design using JAVAFX.ppt
GUI design using JAVAFX.ppt
 
Session_15_JSTL.pdf
Session_15_JSTL.pdfSession_15_JSTL.pdf
Session_15_JSTL.pdf
 
The World of Web Development 2015 - Part2.pptx
The World of Web Development 2015 - Part2.pptxThe World of Web Development 2015 - Part2.pptx
The World of Web Development 2015 - Part2.pptx
 

Recently uploaded

power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 

Recently uploaded (20)

POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 

Final Database Connectivity in JAVA.ppt

  • 2. DATABASE BASED APPLICATION  Database is used to store data. It is also known as persistent storage as the data is stored and can be retrieved anytime. 2
  • 3. INTRODUCTION  Database  Collection of data  DBMS  Database management system  Storing and organizing data  SQL  Relational database  Structured Query Language  CRUD operation in SQL stands for create, read, update, delete.
  • 4. INTRODUCTION  Relational database  Table  Record  Field, column  Primary key Unique data  SQL statement  Query  Record sets
  • 7. STANDARD ACCESS TO DB A P P L I C A T I O N D R I V E R M G R DBMS Driver 1 DBMS Driver 2 DBMS Driver 3 DBMS 1 DBMS 2 DBMS 3 DB DB DB
  • 8. OPEN DATABASE CONNECTIVITY (ODBC) STANDARD ODBC standard is an interface by which application programs can access and process SQL databases in a DBMS-independent manner. It contains: A Data Source that is the database, its associated DBMS, operating system and network platform A DBMS Driver that is supplied by the DBMS vendor or independent software companies A Driver Manager that is supplied by the vendor of the O/S platform where the application is running
  • 9. ODBC ARCHITECTURE Application Class1 Class2 Driver Manager DriverType1 DriverType2 DriverType3 DataSource2 DataSource1 DataSource3 ODBC
  • 10. ODBC INTERFACE  It is a system independent interface to database environment that requires an ODBC driver to be provided for each database system from which you want to manipulate data.  The database driver bridges the differences between your underlying system calls and the ODBC interface functionality.
  • 11. AN EXAMPLE Application DriverManager Sybase driver mSQL driver Informix driver
  • 12. APPLICATION IN JAVA Application in Java DriverManager Sybase driver mSQL driver Informix driver
  • 13. JAVA SUPPORT FOR ODBC : JDBC  When applications written in Java want to access data sources, they use classes and associated methods provided by Java DBC (JDBC) API.  JDBC is specified as an “interface”.  An interface in Java can have many “implementations”.  So it provides a convenient way to realize many “drivers”
  • 14.  JDBC uses drivers to translate generalized JDBC calls into vendor-specific database calls  Drivers exist for most popular databases  Four Classes of JDBC drivers exist Type I Type II Type III Type IV JDBC Drivers
  • 15.  Type I driver provides mapping between JDBC and access API of a database  The access API calls the native API of the database to establish communication  A common Type I driver defines a JDBC to ODBC bridge  ODBC is the database connectivity for databases  JDBC driver translates JDBC calls to corresponding ODBC calls  Thus if ODBC driver exists for a database this bridge can be used to communicate with the database from a Java application  Inefficient and narrow solution  Inefficient, because it goes through multiple layers  Narrow, since functionality of JDBC code limited to whatever ODBC supports JDBC Drivers (Type I) Client Application ODBC API Database Driver (Type I) Native API Database Specific Protocol API Protocol
  • 16.  Type II driver communicates directly with native API  Type II makes calls directly to the native API calls  More efficient since there is one less layer to contend with (i.e. no ODBC)  It is dependent on the existence of a native API for a database JDBC Drivers (Type II) Client Application Database Driver (Type II) Native API Database Specific Protocol API Protocol
  • 17.  Type III driver make calls to a middleware component running on another server  This communication uses a database independent net protocol  Middleware server then makes calls to the database using database- specific protocol  The program sends JDBC call through the JDBC driver to the middle tier  Middle-tier may use Type I or II JDBC driver to communicate with the database. JDBC Drivers (Type III) Database Client Application Driver (Type III) Middleware Server Net Protocol Database Specific Protocol
  • 18.  Type IV driver is an all-Java driver that is also called a thin driver  It issues requests directly to the database using its native protocol  It can be used directly on platform with a JVM  Most efficient since requests only go through one layer  Simplest to deploy since no additional libraries or middle-ware JDBC Drivers (Type IV) Database Client Application Driver (Type IV) Database Specific Protocol
  • 19. JDBC ARCHITECTURE (CONT.) Application JDBC Driver  Java code calls JDBC library  JDBC loads a driver  Driver talks to a particular database  An application can work with several databases by using all corresponding drivers
  • 20. JAVA SUPPORT FOR SQL  Java supports embedded SQL.  Also it provides an JDBC API as a standard way to connect to common relational databases.  Java.sql package and an extensive exception hierarchy.
  • 21. DATA SOURCE AND DRIVER  Data source is the data base created using any of the common database applications available.  Your system should have the driver for the database you will be using.  For example your Windows system should have the MS Access Driver.  There are a number of JDBC drivers available.  Information on installing them is available at : http://industry.java.sun.com/products/jdbc/drivers
  • 22. JDBC COMPONENTS  Driver Manager: Loads database drivers, and manages the connection between application & driver.  Driver: Translates API calls to operations for a specific data source.  Connection: A session between an application and a driver.  Statement: A SQL statement to perform a query or an update operation.  Metadata: Information about the returned data, driver and the database.  Result Set : Logical set of columns and rows returned by executing a statement.
  • 23. JDBC CLASSES  Java supports DB facilities by providing classes and interfaces for its components  DriverManager class  Connection interface  Statement interface (to be instantiated with values from the actual SQL statement)  ResultSet interface
  • 24. JDBC PROGRAMMING STEPS 1. Import necessary packages; Ex: import java.sql.*; 2. Load JDBC driver(driver should have been installed) 3. Data source and its location should have been registered. 4. Allocate Connection object, Statement or PreparedStatement object and ResultSet object 5. Execute query using Statement or PreparedStatement object 6. Retrieve data from ResultSet object 7. Close Connection object.
  • 25. BASIC SELECT QUERY  Simplest format of a SELECT query  SELECT * FROM tableName  SELECT * FROM authors  Select specific fields from a table  SELECT authorID, lastName FROM authors authorID lastName 1 Deitel 2 Deitel 3 Nieto 4 Santry Fig. 8.13 authorID and lastName from the authors table.
  • 26. WHERE CLAUSE  specify the selection criteria  SELECT fieldName1, fieldName2, … FROM tableName WHERE criteria  SELECT title, editionNumber, copyright FROM titles WHERE copyright > 1999  WHERE clause condition operators  <, >, <=, >=, =, <>
  • 27. INSERT INTO STATEMENT  Insert a new record into a table  INSERT INTO tableName ( fieldName1, … , fieldNameN ) VALUES ( value1, … , valueN )  INSERT INTO authors ( firstName, lastName ) VALUES ( ‘Sue’, ‘Smith’ ) authorID firstName lastName 1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry 5 Sue Smith Fig. 8.22 T able Authors after an INSERT INTO operation to add a rec ord.
  • 28. UPDATE STATEMENT  Modify data in a table  UPDATE tableName SET fieldName1 = value1, … , fieldNameN = valueN WHERE criteria  UPDATE authors SET lastName = ‘Jones’ WHERE lastName = ‘Smith’ AND firstName = ‘Sue’ authorID firstName lastName 1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry 5 Sue Jones Fig. 8.23 T able authors after an UPDATE operation to c hange a rec ord.
  • 29. DELETE FROM STATEMENT  Remove data from a table  DELETE FROM tableName WHERE criteria  DELETE FROM authors WHERE lastName = ‘Jones’ AND firstName = ‘Sue’ authorID firstName lastName 1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry Fig. 8.24 T able authors after a DELETE operation to remove a rec ord.
  • 31. 32
  • 32. STEP 1: LOAD THE DRIVER  Loading drivers – An appropriate driver must be loaded using the statement shown below before connecting to a databases 33
  • 33. STEP 2:DEFINE THE CONNECTION URL  To connect to a database, use the static method getConnection(databaseURL) : e.g. Connection conn1 = DriverManager.getConnection (databaseURL); 34
  • 34. EXAMPLE 1 public static final String DB_NAME ="registration.db"; public static final String CONNECTION_STRING = "jdbc: sqlite: D:databases"+DB_NAME; Connection conn1 = DriverManager.getConnection(CONNECTION_STRIN G); 35
  • 36. STEP 3: ESTABLISH THE CONNECTION  The following statement creates a Connection object: Connection conn1; conn1 = DriverManager.getConnection(url); 37
  • 37. STEP 4: CRATING STATEMENT OR PREPARED STATEMENT  Statement and PreparedStatement interface defines the methods and properties that enable you to send SQL commands and receive data from your database.  Once a Connection object is created, you can create statements for executing SQL statements as follows: Statement st = conn1.createStatement(); PreparedStatement ps= conn1.prepareStatement(); 38
  • 38. METHODS OF STATEMENT INTERFACE  boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false.  Use this method to execute SQL DDL statements  int executeUpdate (String SQL): Returns the number of rows affected by the execution of the SQL statement.  Use this method to execute SQL statements for which you expect to get a number of rows affected. - for example, an INSERT, UPDATE, or DELETE statement.  ResultSet executeQuery (String SQL): Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement. 39
  • 39. STEP 5: EXECUTE A QUERY USING THE STATEMENT An SQL query statement can be executed using String queryCheck = "SELECT * from login"; rs = st.executeQuery(queryCheck);  An SQL update statement can be executed using executeUpdate(String sql),  Example: st.executeUpdate("INSERT INTO authors ( firstName, lastName ) VALUES ( 'Sue', 'Smith' )" ); 40
  • 40. RESULTSET  The SELECT statement is the standard way to select rows from a database and view them in a result set.  The java.sql.ResultSet interface represents the result set of a database query.  A ResultSet object maintains a cursor that points to the current row in the result set.  The term "result set" refers to the row and column data contained in a ResultSet object.  41
  • 41. RESULTSET  ResultSet objects provide access to the tables generated as results of executing a Statement queries  Only one ResultSet per Statement can be open at the same time!  The table rows are retrieved in sequence  A ResultSet maintains a cursor pointing to its current row  The next() method moves the cursor to the next row
  • 42. RESULTSET METHODS  boolean next()  activates the next row  the first call to next() activates the first row  returns false if there are no more rows  Type getType(int columnIndex)  returns the given field as the given type  indices start at 1 and not 0  Type getType(String columnName)  same, but uses name of field  int findColumn(String columnName)  looks up column index given column name
  • 43. STEP 6: PROCESSING RESULT  The result of the query is returned in ResultSet, Example:  ResultSet rs = st.executeQuery(queryCheck); Eg: rs = st.executeQuery(queryCheck); while(rs.next()){ s=rs.getString("login_name"); System.out.println("login= "+s); p=rs.getString("password"); System.out.println("password= "+p); } 44
  • 45. ABOUT PREPARED STATEMENTS  Extends functionality of Statement interface  Gives the flexibility of supplying arguments dynamically.  They are parsed (compiled) by the DBMS only once  Column values can be set after compilation  Instead of values, use ‘?’  The setXXX() methods bind values to the parameters, where XXX represents the Java data type of the value you wish to bind to the input parameter.
  • 46. STEP 5: EXECUTE A QUERY USING THE PREPAREDSTATEMENT  Can execute query using execute(), executeQuery() and executeUpdate()  Example: ps.executeUpdate("update customer set acctype=? where cname=?" ); 47
  • 48. 49 STEP 7:CLEANING UP AFTER YOURSELF  Remember to close the Connections, Statements, Prepared Statements and Result Sets con.close(); stmt.close(); rs.close()
  • 49. SELECT QUERY ID fname lname 1 John Smith 2 Paul Dietel 3 Tem Neito 50 ResultSet rs= st.executeQuery(“SELECT *FROM employee”); while(rs.next()){ int id= rs.getInt(1); String f_name = rs.getString(“fname”); String l_name = rs. getString(“lname”); } Table: employee
  • 50. SELECT QUERY ID fname lname 1 John Smith 2 Paul Dietel 3 Tem Neito 51 String selectquery = “SELECT *FROM employee WHERE lname=?”; PreparedStatement ps = con.prepareStatement(selectquery) ; ps.setSting(1, “Smith”); ResultSet rs= ps.executeQuery(); while(rs.next()){ int id= rs.getInt(1); String f_name = rs.getString(“fname”); String l_name = rs. getString(“lname”); }
  • 51. INSERT QUERY int id=122; String f_name=“John”; String l_name= “Mathew”; String INSERT_QUERY = "INSERT INTO employee (ID, fname, lname) VALUES (?, ?, ?)"; PreparedStatement ps = con.prepareStatement(INSERT_QUERY) ; ps.setInt(1, id); ps.setString(2, f_name); ps.setString(3, l_name); ps.executeUpdate(); 52
  • 52. UPDATE QUERY String updatequery = “UPDATE employee SET lname = ? fname = ? WHERE ID= ?” ; PreparedStatement ps = con.prepareStatement(updatequery); ps.setString(1, “Allamaraju”); ps.setString(2, “M”); ps.setInt(3, 123); ps.executeUpdate(); 53
  • 53. DELETE QUERY String deleteQuery = "DELETE FROM employee WHERE fname = ?"; PreparedStatement ps = con.prepareStatement(deleteQuery); ps.setString(1,”John”); int result = ps.executeUpdate(); System.out.println(result + “Row deleted”); 54
  • 54. MAPPING JAVA TYPES TO SQL TYPES SQL type Java Type CHAR, VARCHAR, LONGVARCHAR String NUMERIC, DECIMAL java.math.BigDecimal BIT boolean TINYINT byte SMALLINT short INTEGER int BIGINT long REAL float FLOAT, DOUBLE double BINARY, VARBINARY, LONGVARBINARY byte[] DATE java.sql.Date TIME java.sql.Time TIMESTAMP java.sql.Timestamp
  • 55. SUMMARY  JDBC allows you to write Java programs that manipulate a database  A driver (often a separate product) is required that facilitates access  Key classes: Connection, Statement, PreparedStatement, and ResultSet