SlideShare una empresa de Scribd logo
1 de 32
Connectivity in SQL & JDBC
Presented by:
Harshita Joshi
JDBC
• JDBC is J2SE technology.
• It is data accessing technology from sun
microsystem
• JDBC is a specification which is provided by
sun microsystem for driver manufacturers
• JDBC is API
JDBC Architecture
JDBC client
• Any resources sake request making program is
known as JDBC client
Application JDBC Driver
Responsibilities of JDBC client
• Establishing connection with database
• Submitting appropriate SQL statement to the
DBMS to perform CRUD operation
• Processing and presenting the result
• Deal with Exception
• After performing crude operation closing
connection
JDBC API
• JDBC API is collection of library methods,
using which our java program perform CRUD
operation on database
• To make API available for our program we
have to import java.sql package
DriverManager
• DriverManager is a library class or java.sql
package which is used for establishing
connection
• After receiving connection request from JDBC
client
• After establishing connection DriverManager
rolls end
JDBC Driver
• JDBC driver is a translation software which is
written in java.
• According to JDBC specification i.e Driver
manufacturers implements JDBC API.
JDBC Drivers
• JDBC-ODBC Bridge drivers (follows ODBC
standards)
• Partly Java – Partly Native (this does not use
any standards)
• Pure Java – Net Protocol Drivers
• Pure Java Drivers (also called Type4Drivers,
most popular one)
Type 1 Driver (jdbc - odbc bridge
driver )
Java App
that uses
JDBC API
Jdbc
driver
type1
ODBC Driver
for Oracle
ODBC Driver
for MS-Access
Vendor
DB
Library
for Oracle
Oracle
DB
Vendor
DB
Library
for M S
Access
MS
Access
Type 4 Driver
(Native Protocol All Java Driver)
Java App
that uses
JDBC API
Jdbc
driver
type4
Oracle
DB
Jdbc
driver
type4
MS
Access
Steps to develop java/jdbc App
• Load the JDBC Driver class and register with
DriverManager
• Establish the connection with database s/w
• Prepare Statement object
• Execute the query
• Get result and process the result
• Close the connection
Loading & Registering a Driver
• The driver class libraries need to be in the
CLASSPATH for the Java compiler and for
the Java virtual machine
• Class.forName(string).newInstance();
• Eg:
Class.forName("com.microsoft.jdbc.sqlserv
er.SQLServerDriver");
Establishing a Connection
• A connection string includes the literal jdbc:,
followed by the name of the driver and a URL to
the database
• Connection conn =
DriverManager.getConnection(string);
• Connection connection =
DriverManager.getConnection(
"jdbc:microsoft:sqlserver://127.0.0.1ABCD:1443;”
+ “DatabaseName=JDBCDB","username",
"password");
Ex- String url = "jdbc:odbc:datasource";
try {
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection(url);
}
catch (ClassNotFoundException e)
{ e.printStackTrace(); }
catch (SQLException e)
{ e.printStackTrace(); }
Statement
• Acts as a courier service to send queries to the
db software.
• A Statement object is used for executing a
static SQL statement and obtaining the results
produced by it.
a. Create statement
Statement stmt = conn.createStatement();
stmt object sends SQL commands to database
– Methods
• executeQuery() for SELECT statements
• executeUpdate() for INSERT, UPDATE, DELETE,
statements
b. Send SQL statements
– stmt.executeQuery(“SELECT …”);
– stmt.executeUpdate(“INSERT …”);
ResultSet
• A ResultSet object is a java object which can store
bunch of selected rows given by select query
execution.
• Only one ResultSet per Statement can be open at
once.
• The table rows are retrieved in sequence.
• A ResultSet maintains a cursor pointing to its
current row of data.
• The 'next' method moves the cursor to the next row.
• boolean next()
– activates the next row
– the first call to next() activates the first row
– returns false if there are no more rows
• void close()
– disposes of the ResultSet
– allows you to re-use the Statement that created it
• Type getType(int columnIndex)
– returns the given field as the given type
– fields indexed starting at 1 (not 0)
• Type getType(String columnName)
– same, but uses name of field
– less efficient
ResultSet Methods
• String getString(int columnIndex)
• boolean getBoolean(int columnIndex)
• byte getByte(int columnIndex)
• short getShort(int columnIndex)
• int getInt(int columnIndex)
• long getLong(int columnIndex)
• float getFloat(int columnIndex)
• double getDouble(int columnIndex)
• Date getDate(int columnIndex)
• Time getTime(int columnIndex)
• Timestamp getTimestamp(int columnIndex)
Process results
• Result of a SELECT statement (rows/columns)
returned as a ResultSet object
– ResultSet rs =
stmt.executeQuery("SELECT * FROM users");
• Step through each row in the result
– rs.next()
• Get column values in a row
– String userid = rs.getString(“userid”);
– int type = rs.getInt(“type”);
ResultSet rs = stmt.executeQuery("SELECT *
FROM users");
while (rs.next()) {
String userid = rs.getString(1);
String firstname = rs.getString(“firstname”);
String lastname = rs.getString(“lastname”);
String password = rs.getString(4);
int type = rs.getInt(“type”);
System.out.println(userid + ” ” + firstname + ” ”
+ lastname + ” ” + password + ” ” + type);
}
users table
userid firstname lastname password type
Bob Bob King cat 0
John John Smith pass 1
Program
import java.sql.*;
public class Tester {
public static void main(String[] args) {
try {
// Load JDBC driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Make connection
String url =
“jdbc:mysql://128.100.53.33/GRP?user=USER&password=PASS”
Connection conn = DriverManager.getConnection(url);
// Create statement
Statement stmt = conn.createStatement();
// Print the users table
ResultSet rs = stmt.executeQuery("SELECT *
FROM users");
while (rs.next()) {
...
}
// Cleanup
rs.close(); stmt.close(); conn.close();
} catch (Exception e) {
System.out.println("exception " + e);
}
}
Limitations of Statement Object
• DB s/w parses the same query multiple no. of
times and executes, fetches the o/p .
• Framing query for simple Statement object
using variable is quite unnecessary.
• Network traffic to the DB s/w is heavy since
same query goes multiple no. of times to the
DB s/w.
• To overcome these problems use precompiled
queries.
PreparedStatement Object
• A query that goes and resides on the DB s/w without
values by becoming parsed query is a precompiled
query.
• Precompiled queries will be parsed only once, but
capable of executing multiple times with same or
different values.
• PreparedStatement object represents this
precompiled query.
• When to use Statement object and
PreparedStatement object ?
Steps to work with
PreparedStatement
• Prepare the query having positional parameters.
String query=“insert into item values(?,?,?,?)”;
• Positional parameter indicates value to that query
will be set afterwards.
• Create PreparedStatement object.
• PreparedStatement ps=con.prepareStatement(query);
• Set the values for positional paremeters using
setType(-,-) methods.
–ps.setInt(-,-), ps.setString(-,-)
• Execute the query
–int result = ps.executeUpdate();
• For more executions repeat step 3 & 4.
• Close PreparedStatement object
–ps.close()
• PreparedStatement ps = con.prepareStatement ("insert
into emp values(?,?,?)");
• ps.setInt(1,23);
• ps.setString(2,"Roshan");
• ps.setString(3, "CEO");
• ps.executeUpdate();
• ps.close()
JDBC Object Classes
• DriverManager
– Loads, chooses drivers
• Driver
– connects to actual database
• Connection
– a series of SQL statements to and from the DB
• Statement
– a single SQL statement
• ResultSet
– the records returned from a Statement
JDBC Class Usage
DriverManager
Driver
Connection
Statement
ResultSet
Thank you!

Más contenido relacionado

La actualidad más candente

Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryPray Desai
 
Utilized JAXB to generate POJOs automatically
Utilized JAXB to generate POJOs automaticallyUtilized JAXB to generate POJOs automatically
Utilized JAXB to generate POJOs automaticallyGuo Albert
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackGaryCoady
 
Best Practices for Interoperable XML Databinding with JAXB
Best Practices for Interoperable XML Databinding with JAXBBest Practices for Interoperable XML Databinding with JAXB
Best Practices for Interoperable XML Databinding with JAXBMartin Grebac
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffJAX London
 
Data weave (MuleSoft)
Data weave (MuleSoft)Data weave (MuleSoft)
Data weave (MuleSoft)Nandu List5
 
Java serialization
Java serializationJava serialization
Java serializationSujit Kumar
 
An Introduction to Scala
An Introduction to ScalaAn Introduction to Scala
An Introduction to ScalaBrent Lemons
 
Java Serialization
Java SerializationJava Serialization
Java Serializationimypraz
 
Java- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solutionJava- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solutionMazenetsolution
 

La actualidad más candente (19)

Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
 
Jdbc
JdbcJdbc
Jdbc
 
Css
CssCss
Css
 
Utilized JAXB to generate POJOs automatically
Utilized JAXB to generate POJOs automaticallyUtilized JAXB to generate POJOs automatically
Utilized JAXB to generate POJOs automatically
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
Best Practices for Interoperable XML Databinding with JAXB
Best Practices for Interoperable XML Databinding with JAXBBest Practices for Interoperable XML Databinding with JAXB
Best Practices for Interoperable XML Databinding with JAXB
 
Apache spark
Apache sparkApache spark
Apache spark
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
Data weave (MuleSoft)
Data weave (MuleSoft)Data weave (MuleSoft)
Data weave (MuleSoft)
 
Javasession6
Javasession6Javasession6
Javasession6
 
Java serialization
Java serializationJava serialization
Java serialization
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
Scala basic
Scala basicScala basic
Scala basic
 
An Introduction to Scala
An Introduction to ScalaAn Introduction to Scala
An Introduction to Scala
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Java- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solutionJava- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solution
 

Similar a Jdbc presentation

BI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBCBI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBCSimba Technologies
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionMazenetsolution
 
JDBC Connectivity Model
JDBC Connectivity ModelJDBC Connectivity Model
JDBC Connectivity Modelkunj desai
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivityarikazukito
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programmingchhaichivon
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptkingkolju
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.pptNaveenKumar648465
 
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part IPROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part ISivaSankari36
 

Similar a Jdbc presentation (20)

BI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBCBI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
JDBC Connectivity Model
JDBC Connectivity ModelJDBC Connectivity Model
JDBC Connectivity Model
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
Unit 5.pdf
Unit 5.pdfUnit 5.pdf
Unit 5.pdf
 
Jdbc
JdbcJdbc
Jdbc
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
22jdbc
22jdbc22jdbc
22jdbc
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.ppt
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
 
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part IPROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part I
 
Jdbc
JdbcJdbc
Jdbc
 

Último

Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfRagavanV2
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...tanu pandey
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spaintimesproduction05
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 

Último (20)

Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spain
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 

Jdbc presentation

  • 1. Connectivity in SQL & JDBC Presented by: Harshita Joshi
  • 2. JDBC • JDBC is J2SE technology. • It is data accessing technology from sun microsystem • JDBC is a specification which is provided by sun microsystem for driver manufacturers • JDBC is API
  • 4. JDBC client • Any resources sake request making program is known as JDBC client Application JDBC Driver
  • 5. Responsibilities of JDBC client • Establishing connection with database • Submitting appropriate SQL statement to the DBMS to perform CRUD operation • Processing and presenting the result • Deal with Exception • After performing crude operation closing connection
  • 6. JDBC API • JDBC API is collection of library methods, using which our java program perform CRUD operation on database • To make API available for our program we have to import java.sql package
  • 7. DriverManager • DriverManager is a library class or java.sql package which is used for establishing connection • After receiving connection request from JDBC client • After establishing connection DriverManager rolls end
  • 8. JDBC Driver • JDBC driver is a translation software which is written in java. • According to JDBC specification i.e Driver manufacturers implements JDBC API.
  • 9. JDBC Drivers • JDBC-ODBC Bridge drivers (follows ODBC standards) • Partly Java – Partly Native (this does not use any standards) • Pure Java – Net Protocol Drivers • Pure Java Drivers (also called Type4Drivers, most popular one)
  • 10. Type 1 Driver (jdbc - odbc bridge driver ) Java App that uses JDBC API Jdbc driver type1 ODBC Driver for Oracle ODBC Driver for MS-Access Vendor DB Library for Oracle Oracle DB Vendor DB Library for M S Access MS Access
  • 11. Type 4 Driver (Native Protocol All Java Driver) Java App that uses JDBC API Jdbc driver type4 Oracle DB Jdbc driver type4 MS Access
  • 12. Steps to develop java/jdbc App • Load the JDBC Driver class and register with DriverManager • Establish the connection with database s/w • Prepare Statement object • Execute the query • Get result and process the result • Close the connection
  • 13. Loading & Registering a Driver • The driver class libraries need to be in the CLASSPATH for the Java compiler and for the Java virtual machine • Class.forName(string).newInstance(); • Eg: Class.forName("com.microsoft.jdbc.sqlserv er.SQLServerDriver");
  • 14. Establishing a Connection • A connection string includes the literal jdbc:, followed by the name of the driver and a URL to the database • Connection conn = DriverManager.getConnection(string); • Connection connection = DriverManager.getConnection( "jdbc:microsoft:sqlserver://127.0.0.1ABCD:1443;” + “DatabaseName=JDBCDB","username", "password");
  • 15. Ex- String url = "jdbc:odbc:datasource"; try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection(url); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }
  • 16. Statement • Acts as a courier service to send queries to the db software. • A Statement object is used for executing a static SQL statement and obtaining the results produced by it.
  • 17. a. Create statement Statement stmt = conn.createStatement(); stmt object sends SQL commands to database – Methods • executeQuery() for SELECT statements • executeUpdate() for INSERT, UPDATE, DELETE, statements b. Send SQL statements – stmt.executeQuery(“SELECT …”); – stmt.executeUpdate(“INSERT …”);
  • 18. ResultSet • A ResultSet object is a java object which can store bunch of selected rows given by select query execution. • Only one ResultSet per Statement can be open at once. • The table rows are retrieved in sequence. • A ResultSet maintains a cursor pointing to its current row of data. • The 'next' method moves the cursor to the next row.
  • 19. • boolean next() – activates the next row – the first call to next() activates the first row – returns false if there are no more rows • void close() – disposes of the ResultSet – allows you to re-use the Statement that created it • Type getType(int columnIndex) – returns the given field as the given type – fields indexed starting at 1 (not 0) • Type getType(String columnName) – same, but uses name of field – less efficient
  • 20. ResultSet Methods • String getString(int columnIndex) • boolean getBoolean(int columnIndex) • byte getByte(int columnIndex) • short getShort(int columnIndex) • int getInt(int columnIndex) • long getLong(int columnIndex) • float getFloat(int columnIndex) • double getDouble(int columnIndex) • Date getDate(int columnIndex) • Time getTime(int columnIndex) • Timestamp getTimestamp(int columnIndex)
  • 21. Process results • Result of a SELECT statement (rows/columns) returned as a ResultSet object – ResultSet rs = stmt.executeQuery("SELECT * FROM users"); • Step through each row in the result – rs.next() • Get column values in a row – String userid = rs.getString(“userid”); – int type = rs.getInt(“type”);
  • 22. ResultSet rs = stmt.executeQuery("SELECT * FROM users"); while (rs.next()) { String userid = rs.getString(1); String firstname = rs.getString(“firstname”); String lastname = rs.getString(“lastname”); String password = rs.getString(4); int type = rs.getInt(“type”); System.out.println(userid + ” ” + firstname + ” ” + lastname + ” ” + password + ” ” + type); } users table userid firstname lastname password type Bob Bob King cat 0 John John Smith pass 1
  • 23. Program import java.sql.*; public class Tester { public static void main(String[] args) { try { // Load JDBC driver Class.forName("com.mysql.jdbc.Driver").newInstance(); // Make connection String url = “jdbc:mysql://128.100.53.33/GRP?user=USER&password=PASS” Connection conn = DriverManager.getConnection(url);
  • 24. // Create statement Statement stmt = conn.createStatement(); // Print the users table ResultSet rs = stmt.executeQuery("SELECT * FROM users"); while (rs.next()) { ... } // Cleanup rs.close(); stmt.close(); conn.close(); } catch (Exception e) { System.out.println("exception " + e); } }
  • 25. Limitations of Statement Object • DB s/w parses the same query multiple no. of times and executes, fetches the o/p . • Framing query for simple Statement object using variable is quite unnecessary. • Network traffic to the DB s/w is heavy since same query goes multiple no. of times to the DB s/w. • To overcome these problems use precompiled queries.
  • 26. PreparedStatement Object • A query that goes and resides on the DB s/w without values by becoming parsed query is a precompiled query. • Precompiled queries will be parsed only once, but capable of executing multiple times with same or different values. • PreparedStatement object represents this precompiled query. • When to use Statement object and PreparedStatement object ?
  • 27. Steps to work with PreparedStatement • Prepare the query having positional parameters. String query=“insert into item values(?,?,?,?)”; • Positional parameter indicates value to that query will be set afterwards. • Create PreparedStatement object.
  • 28. • PreparedStatement ps=con.prepareStatement(query); • Set the values for positional paremeters using setType(-,-) methods. –ps.setInt(-,-), ps.setString(-,-) • Execute the query –int result = ps.executeUpdate(); • For more executions repeat step 3 & 4. • Close PreparedStatement object –ps.close()
  • 29. • PreparedStatement ps = con.prepareStatement ("insert into emp values(?,?,?)"); • ps.setInt(1,23); • ps.setString(2,"Roshan"); • ps.setString(3, "CEO"); • ps.executeUpdate(); • ps.close()
  • 30. JDBC Object Classes • DriverManager – Loads, chooses drivers • Driver – connects to actual database • Connection – a series of SQL statements to and from the DB • Statement – a single SQL statement • ResultSet – the records returned from a Statement