SlideShare a Scribd company logo
JDBC
• File vs Database
• JDBC
• Fundamental Steps in JDBC
• Statement,PreparedStatement,CallableStatement
• ResultSet
• Practice basic JDBC programming with simple programming
using JDBC Driver
• Understand Advance JDBC programming
Content
File vs Database
DBMS:
• coordinates both the physical and the logical access to the data
• reduces the amount of data duplication by ensuring that a physical piece of data is
available to all programs authorized to have access to it.
• designed to allow flexible access to data (i.e., queries)
• designed to coordinate multiple users accessing the same data at the same time
File:
• coordinates only the physical access.
• data written by one program in a file-processing system may not be readable by
another program.
• designed to allow predetermined access to data (i.e., compiled programs).
• designed to allow one or more programs to access different data files at the same
time.
JDBC
JDBC Driver
JAVA Applet/
Application Database
JDBC Call
Database
Command
• JDBC
– JDBC is a standard interface for connecting to relational databases from Java
– The JDBC Classes and Interfaces are in the java.sql package
– JDBC is Java API for executing SQL statements
• Provides a standard API for tool/database developers
• Possible to write database applications using a pure Java API
• Easy to send SQL statements to virtually any relational database
• What does JDBC do?
– Establish a connection with a database
– Send SQL statements
– Process the results
JDBC
• 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
• Ideal: can change database engines without changing any application
code (not always in practice)
JDBC Driver
JAVA Applet/
Application Database
JDBC Call
Database
Command
Fundamental Step in JDBC
• Load the driver
• Define the connection URL
• Establish the connection
• Create a Statement object
• Execute a query using the Statement
• Process the result
• Close the connection
Loading the Driver
• We can register the driver indirectly using the
statement
Class.forName(“org.postgresql.Driver");
• Class.forName loads the specified class
• When Driver is loaded, it automatically
– creates an instance of itself
– registers this instance with the DriverManager
• Hence, the driver class can be given as an argument of
the application
8
Connecting to the Database
• Every database is identified by a URL
• Given a URL, DriverManager looks for the driver
that can talk to the corresponding database
• DriverManager tries all registered drivers, until a
suitable one is found
Connection Driver and URL
RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/
databaseName
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port
Number:databaseName
DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port
Number/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port
Number/databaseName
Postgres org.postgresql.Driver jdbc:postgresql://hostname:port/d
atabaseName
Access sun.jdbc.odbc.JdbcOdbcDriver
Note : Both the ":" and "@" are mandatory
Syntax:
Connection conn = DriverManager.getConnection(URL, username, passwd);
Connection conn = DriverManager.getConnection(URL)
Connection conn = DriverManager.getConnection(URL,properties object)
Example:
import java.util.*;
String URL = "jdbc:postgresql://1.1.1.1:5432/test";
Properties info = new Properties( );
info.put( "user", "username" );
info.put( "password", "password" );
Connection conn = DriverManager.getConnection(URL, info);
Note: Remember to close connection using conn.close(); or place it in finally block
Connect to Database
Interaction with the Database
• We use Statement objects in order to
– Query the database
– Update the database
• Three different interfaces are used:
Statement, PreparedStatement, CallableStatement
• All are interfaces, hence cannot be instantiated
• They are created by the Connection
Querying with Statement
• The executeQuery method returns a ResultSet object
representing the query result.
String queryStr =
"SELECT * FROM tbStudent" +
"WHERE name = ‘sok'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(queryStr);
Changing DB with Statement
String deleteStr =
"DELETE FROM tbStudent" +
"WHERE lname = ‘sok'";
Statement stmt = con.createStatement();
int delnum = stmt.executeUpdate(deleteStr);
• executeUpdate is used for data manipulation: insert, delete,
update, create table, etc. (anything other than querying!)
• executeUpdate returns the number of rows modified
14
About Prepared Statements
• Prepared Statements are used for queries that are
executed many times
• They are parsed (compiled) by the DBMS only once
• Column values can be set after compilation
• Instead of values, use ‘?’
15
Querying with PreparedStatement
String queryStr =
"SELECT * FROM tbStudent" +
"WHERE name= ? and id= ?";
PreparedStatement pstmt =
con.prepareStatement(queryStr);
pstmt.setString(1, “sok");
pstmt.setInt(2, 1);
ResultSet rs = pstmt.executeQuery();
16
Statements vs.
PreparedStatements: Be Careful!
• Will this work?
• No!!! A ‘?’ can only be used to represent a
column value
PreparedStatement pstmt =
con.prepareStatement("select * from ?");
pstmt.setString(1, myFavoriteTableString);
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
• JDBC returns the results of a query in a ResultSet object
– ResultSet object contains all of the rows which satisfied the conditions
in an SQL statement
• A ResultSet object maintains a cursor pointing to its current
row of data
– Use next() to step through the result set row by row
• next() returns TRUE if there are still remaining records
– getString(), getInt(), and getXXX() assign each value to a Java
variable
Record 1 Record 2 Record 3 Record 4
ResultSetInternal Pointer
The internal pointer starts one before the first record
19
ResultSet Example
Statement stmt = con.createStatement();
ResultSet rs = stmt.
executeQuery("select id,name from tbStudent");
// Print the result
while(rs.next()) {
System.out.print(rs.getInt(1) + ":");
System.out.println(rs.getString(“name"));
}
20
ResultSet Meta-Data
ResultSetMetaData rsmd = rs.getMetaData();
int numcols = rsmd.getColumnCount();
for (int i = 1 ; i <= numcols; i++) {
System.out.print(rsmd.getColumnLabel(i)+" ");
}
A ResultSetMetaData is an object that can be used to
get information about the properties of the columns
in a ResultSet object
An example: write the columns of the result set
21
Cleaning Up After Yourself
• Remember to close the Connections,
Statements, Prepared Statements and Result
Sets
con.close();
stmt.close();
pstmt.close();
rs.close()
22
Dealing With Exceptions
• An SQLException is actually a list of
exceptions
catch (SQLException e) {
while (e != null) {
System.out.println(e.getSQLState());
System.out.println(e.getMessage());
System.out.println(e.getErrorCode());
e = e.getNextException();
}
}
23
Transactions and JDBC
• Transaction: more than one statement that must all
succeed (or all fail) together
– e.g., updating several tables due to customer purchase
• If one fails, the system must reverse all previous actions
• Also can’t leave DB in inconsistent state halfway through
a transaction
• COMMIT = complete transaction
• ROLLBACK = cancel all actions
24
Example
• Suppose we want to transfer money from bank account
13 to account 72:
PreparedStatement pstmt =
con.prepareStatement("update BankAccount
set amount = amount + ?
where accountId = ?");
pstmt.setInt(1,-100);
pstmt.setInt(2, 13);
pstmt.executeUpdate();
pstmt.setInt(1, 100);
pstmt.setInt(2, 72);
pstmt.executeUpdate();
What happens if this
update fails?
25
Transaction Management
• Transactions are not explicitly opened and closed
• The connection has a state called AutoCommit mode
• if AutoCommit is true, then every statement is
automatically committed
• if AutoCommit is false, then every statement is added to
an ongoing transaction
• Default: true
26
AutoCommit
• If you set AutoCommit to false, you must explicitly commit or
rollback the transaction using Connection.commit() and
Connection.rollback()
• Note: DDL statements (e.g., creating/deleting tables) in a
transaction may be ignored or may cause a commit to occur
– The behavior is DBMS dependent
setAutoCommit(boolean val)

More Related Content

What's hot

A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
Mindfire Solutions
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
mahir jain
 
java Jdbc
java Jdbc java Jdbc
java Jdbc
Ankit Desai
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
kamal kotecha
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
Madishetty Prathibha
 
Java basic
Java basicJava basic
Java basic
Sonam Sharma
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
Farooq Baloch
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Ajay Sharma
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
Mumbai Academisc
 
Java layoutmanager
Java layoutmanagerJava layoutmanager
Java layoutmanager
Arati Gadgil
 
JVM
JVMJVM
Java
JavaJava
Java Virtual Machine (JVM), Difference JDK, JRE & JVM
Java Virtual Machine (JVM), Difference JDK, JRE & JVMJava Virtual Machine (JVM), Difference JDK, JRE & JVM
Java Virtual Machine (JVM), Difference JDK, JRE & JVM
shamnasain
 
Features of java
Features of javaFeatures of java
Features of java
WILLFREDJOSE W
 
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript Programming
Haim Michael
 
Namespaces in C#
Namespaces in C#Namespaces in C#
Namespaces in C#
yogita kachve
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machine
Nikhil Sharma
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
ParminderKundu
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
Tanmoy Barman
 
Compiler Design LR parsing SLR ,LALR CLR
Compiler Design LR parsing SLR ,LALR CLRCompiler Design LR parsing SLR ,LALR CLR
Compiler Design LR parsing SLR ,LALR CLR
Riazul Islam
 

What's hot (20)

A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
java Jdbc
java Jdbc java Jdbc
java Jdbc
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
 
Java basic
Java basicJava basic
Java basic
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Java layoutmanager
Java layoutmanagerJava layoutmanager
Java layoutmanager
 
JVM
JVMJVM
JVM
 
Java
JavaJava
Java
 
Java Virtual Machine (JVM), Difference JDK, JRE & JVM
Java Virtual Machine (JVM), Difference JDK, JRE & JVMJava Virtual Machine (JVM), Difference JDK, JRE & JVM
Java Virtual Machine (JVM), Difference JDK, JRE & JVM
 
Features of java
Features of javaFeatures of java
Features of java
 
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript Programming
 
Namespaces in C#
Namespaces in C#Namespaces in C#
Namespaces in C#
 
Java virtual machine
Java virtual machineJava virtual machine
Java virtual machine
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Compiler Design LR parsing SLR ,LALR CLR
Compiler Design LR parsing SLR ,LALR CLRCompiler Design LR parsing SLR ,LALR CLR
Compiler Design LR parsing SLR ,LALR CLR
 

Viewers also liked

Types of Drivers in JDBC
Types of Drivers in JDBCTypes of Drivers in JDBC
Types of Drivers in JDBC
Hemant Sharma
 
Overview Of JDBC
Overview Of JDBCOverview Of JDBC
Overview Of JDBC
Mindfire Solutions
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
Arati Gadgil
 
Aula 01 a Tecnologia da informação e o mercado de trabalho
Aula 01   a Tecnologia da informação e o mercado de trabalhoAula 01   a Tecnologia da informação e o mercado de trabalho
Aula 01 a Tecnologia da informação e o mercado de trabalho
Isac Castro
 
PaulS compounds1
PaulS compounds1PaulS compounds1
PaulS compounds1
Tyler Harris
 
Grandes mentes piensan parecido. Mentes creativas piensan juntas.
Grandes mentes piensan parecido. Mentes creativas piensan juntas.Grandes mentes piensan parecido. Mentes creativas piensan juntas.
Grandes mentes piensan parecido. Mentes creativas piensan juntas.
E E S N° 17
 
Grupo
GrupoGrupo
Grupo
lomeli-29
 
​Big data and the examined life
​Big data and the examined life​Big data and the examined life
​Big data and the examined life
Sherry Jones
 
Srinivas_CH
Srinivas_CHSrinivas_CH
Srinivas_CH
Srinivas CH
 
Facebook And Pinterest Take Big Data (BI, Analytics and Machine Learning) To ...
Facebook And Pinterest Take Big Data (BI, Analytics and Machine Learning) To ...Facebook And Pinterest Take Big Data (BI, Analytics and Machine Learning) To ...
Facebook And Pinterest Take Big Data (BI, Analytics and Machine Learning) To ...
Intellectyx Inc
 
Trabajo de financiamient orev
Trabajo de financiamient orevTrabajo de financiamient orev
Trabajo de financiamient orev
Yosmar Andreina Brito Montaña
 
Katty linares
Katty linaresKatty linares
Katty linares
katty linares
 
Proyecto Eratostenes
Proyecto EratostenesProyecto Eratostenes
Proyecto Eratostenes
E E S N° 17
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
Vikas Jagtap
 
Jdbc
JdbcJdbc
MapTaPhut - Unit 1 Boiler log sheet
MapTaPhut - Unit 1 Boiler log sheetMapTaPhut - Unit 1 Boiler log sheet
MapTaPhut - Unit 1 Boiler log sheet
Richard Smith
 
steel pipe fittings, flanges
steel pipe fittings, flangessteel pipe fittings, flanges
steel pipe fittings, flanges
Jinmo pipe fittings
 

Viewers also liked (17)

Types of Drivers in JDBC
Types of Drivers in JDBCTypes of Drivers in JDBC
Types of Drivers in JDBC
 
Overview Of JDBC
Overview Of JDBCOverview Of JDBC
Overview Of JDBC
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
Aula 01 a Tecnologia da informação e o mercado de trabalho
Aula 01   a Tecnologia da informação e o mercado de trabalhoAula 01   a Tecnologia da informação e o mercado de trabalho
Aula 01 a Tecnologia da informação e o mercado de trabalho
 
PaulS compounds1
PaulS compounds1PaulS compounds1
PaulS compounds1
 
Grandes mentes piensan parecido. Mentes creativas piensan juntas.
Grandes mentes piensan parecido. Mentes creativas piensan juntas.Grandes mentes piensan parecido. Mentes creativas piensan juntas.
Grandes mentes piensan parecido. Mentes creativas piensan juntas.
 
Grupo
GrupoGrupo
Grupo
 
​Big data and the examined life
​Big data and the examined life​Big data and the examined life
​Big data and the examined life
 
Srinivas_CH
Srinivas_CHSrinivas_CH
Srinivas_CH
 
Facebook And Pinterest Take Big Data (BI, Analytics and Machine Learning) To ...
Facebook And Pinterest Take Big Data (BI, Analytics and Machine Learning) To ...Facebook And Pinterest Take Big Data (BI, Analytics and Machine Learning) To ...
Facebook And Pinterest Take Big Data (BI, Analytics and Machine Learning) To ...
 
Trabajo de financiamient orev
Trabajo de financiamient orevTrabajo de financiamient orev
Trabajo de financiamient orev
 
Katty linares
Katty linaresKatty linares
Katty linares
 
Proyecto Eratostenes
Proyecto EratostenesProyecto Eratostenes
Proyecto Eratostenes
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Jdbc
JdbcJdbc
Jdbc
 
MapTaPhut - Unit 1 Boiler log sheet
MapTaPhut - Unit 1 Boiler log sheetMapTaPhut - Unit 1 Boiler log sheet
MapTaPhut - Unit 1 Boiler log sheet
 
steel pipe fittings, flanges
steel pipe fittings, flangessteel pipe fittings, flanges
steel pipe fittings, flanges
 

Similar to Jdbc Java Programming

Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
yazidds2
 
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
 
Java JDBC
Java JDBCJava JDBC
Jdbc
JdbcJdbc
Jdbc
JdbcJdbc
Jdbc
lathasiva
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
Mazenetsolution
 
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 Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
Swapnil Kale
 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentation
nrjoshiee
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
Eleonora Ciceri
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
John David Duncan
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
Raji Ghawi
 
Ado
AdoAdo
JDBC
JDBCJDBC
Jsp project module
Jsp project moduleJsp project module
Introduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRIntroduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIR
Peter Elst
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5
Smita B Kumar
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
Haroon Idrees
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
Sasidhar Kothuru
 
Jdbc day-1
Jdbc day-1Jdbc day-1
Jdbc day-1
Soham Sengupta
 

Similar to Jdbc Java Programming (20)

Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
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
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
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 Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentation
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
 
Ado
AdoAdo
Ado
 
JDBC
JDBCJDBC
JDBC
 
Jsp project module
Jsp project moduleJsp project module
Jsp project module
 
Introduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRIntroduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIR
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Jdbc day-1
Jdbc day-1Jdbc day-1
Jdbc day-1
 

Recently uploaded

Penify - Let AI do the Documentation, you write the Code.
Penify - Let AI do the Documentation, you write the Code.Penify - Let AI do the Documentation, you write the Code.
Penify - Let AI do the Documentation, you write the Code.
KrishnaveniMohan1
 
Microsoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptxMicrosoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptx
jrodriguezq3110
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
vaishalijagtap12
 
What is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdfWhat is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdf
kalichargn70th171
 
Computer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdfComputer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdf
chandangoswami40933
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
kalichargn70th171
 
Cost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App DevelopmentCost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App Development
Softradix Technologies
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Vince Scalabrino
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
widenerjobeyrl638
 
Beginner's Guide to Observability@Devoxx PL 2024
Beginner's  Guide to Observability@Devoxx PL 2024Beginner's  Guide to Observability@Devoxx PL 2024
Beginner's Guide to Observability@Devoxx PL 2024
michniczscribd
 
Going AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applicationsGoing AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applications
Alina Yurenko
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
Pedro J. Molina
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
Luigi Fugaro
 
Ensuring Efficiency and Speed with Practical Solutions for Clinical Operations
Ensuring Efficiency and Speed with Practical Solutions for Clinical OperationsEnsuring Efficiency and Speed with Practical Solutions for Clinical Operations
Ensuring Efficiency and Speed with Practical Solutions for Clinical Operations
OnePlan Solutions
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
Paul Brebner
 

Recently uploaded (20)

Penify - Let AI do the Documentation, you write the Code.
Penify - Let AI do the Documentation, you write the Code.Penify - Let AI do the Documentation, you write the Code.
Penify - Let AI do the Documentation, you write the Code.
 
Microsoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptxMicrosoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptx
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
 
What is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdfWhat is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdf
 
Computer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdfComputer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdf
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
 
Cost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App DevelopmentCost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App Development
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
 
bgiolcb
bgiolcbbgiolcb
bgiolcb
 
Beginner's Guide to Observability@Devoxx PL 2024
Beginner's  Guide to Observability@Devoxx PL 2024Beginner's  Guide to Observability@Devoxx PL 2024
Beginner's Guide to Observability@Devoxx PL 2024
 
Going AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applicationsGoing AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applications
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
 
Ensuring Efficiency and Speed with Practical Solutions for Clinical Operations
Ensuring Efficiency and Speed with Practical Solutions for Clinical OperationsEnsuring Efficiency and Speed with Practical Solutions for Clinical Operations
Ensuring Efficiency and Speed with Practical Solutions for Clinical Operations
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
 

Jdbc Java Programming

  • 2. • File vs Database • JDBC • Fundamental Steps in JDBC • Statement,PreparedStatement,CallableStatement • ResultSet • Practice basic JDBC programming with simple programming using JDBC Driver • Understand Advance JDBC programming Content
  • 3. File vs Database DBMS: • coordinates both the physical and the logical access to the data • reduces the amount of data duplication by ensuring that a physical piece of data is available to all programs authorized to have access to it. • designed to allow flexible access to data (i.e., queries) • designed to coordinate multiple users accessing the same data at the same time File: • coordinates only the physical access. • data written by one program in a file-processing system may not be readable by another program. • designed to allow predetermined access to data (i.e., compiled programs). • designed to allow one or more programs to access different data files at the same time.
  • 4. JDBC JDBC Driver JAVA Applet/ Application Database JDBC Call Database Command • JDBC – JDBC is a standard interface for connecting to relational databases from Java – The JDBC Classes and Interfaces are in the java.sql package – JDBC is Java API for executing SQL statements • Provides a standard API for tool/database developers • Possible to write database applications using a pure Java API • Easy to send SQL statements to virtually any relational database • What does JDBC do? – Establish a connection with a database – Send SQL statements – Process the results
  • 5. JDBC • 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 • Ideal: can change database engines without changing any application code (not always in practice) JDBC Driver JAVA Applet/ Application Database JDBC Call Database Command
  • 6. Fundamental Step in JDBC • Load the driver • Define the connection URL • Establish the connection • Create a Statement object • Execute a query using the Statement • Process the result • Close the connection
  • 7. Loading the Driver • We can register the driver indirectly using the statement Class.forName(“org.postgresql.Driver"); • Class.forName loads the specified class • When Driver is loaded, it automatically – creates an instance of itself – registers this instance with the DriverManager • Hence, the driver class can be given as an argument of the application
  • 8. 8 Connecting to the Database • Every database is identified by a URL • Given a URL, DriverManager looks for the driver that can talk to the corresponding database • DriverManager tries all registered drivers, until a suitable one is found
  • 9. Connection Driver and URL RDBMS JDBC driver name URL format MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port Number:databaseName DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number/databaseName Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port Number/databaseName Postgres org.postgresql.Driver jdbc:postgresql://hostname:port/d atabaseName Access sun.jdbc.odbc.JdbcOdbcDriver Note : Both the ":" and "@" are mandatory
  • 10. Syntax: Connection conn = DriverManager.getConnection(URL, username, passwd); Connection conn = DriverManager.getConnection(URL) Connection conn = DriverManager.getConnection(URL,properties object) Example: import java.util.*; String URL = "jdbc:postgresql://1.1.1.1:5432/test"; Properties info = new Properties( ); info.put( "user", "username" ); info.put( "password", "password" ); Connection conn = DriverManager.getConnection(URL, info); Note: Remember to close connection using conn.close(); or place it in finally block Connect to Database
  • 11. Interaction with the Database • We use Statement objects in order to – Query the database – Update the database • Three different interfaces are used: Statement, PreparedStatement, CallableStatement • All are interfaces, hence cannot be instantiated • They are created by the Connection
  • 12. Querying with Statement • The executeQuery method returns a ResultSet object representing the query result. String queryStr = "SELECT * FROM tbStudent" + "WHERE name = ‘sok'"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(queryStr);
  • 13. Changing DB with Statement String deleteStr = "DELETE FROM tbStudent" + "WHERE lname = ‘sok'"; Statement stmt = con.createStatement(); int delnum = stmt.executeUpdate(deleteStr); • executeUpdate is used for data manipulation: insert, delete, update, create table, etc. (anything other than querying!) • executeUpdate returns the number of rows modified
  • 14. 14 About Prepared Statements • Prepared Statements are used for queries that are executed many times • They are parsed (compiled) by the DBMS only once • Column values can be set after compilation • Instead of values, use ‘?’
  • 15. 15 Querying with PreparedStatement String queryStr = "SELECT * FROM tbStudent" + "WHERE name= ? and id= ?"; PreparedStatement pstmt = con.prepareStatement(queryStr); pstmt.setString(1, “sok"); pstmt.setInt(2, 1); ResultSet rs = pstmt.executeQuery();
  • 16. 16 Statements vs. PreparedStatements: Be Careful! • Will this work? • No!!! A ‘?’ can only be used to represent a column value PreparedStatement pstmt = con.prepareStatement("select * from ?"); pstmt.setString(1, myFavoriteTableString);
  • 17. 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
  • 18. ResultSet • JDBC returns the results of a query in a ResultSet object – ResultSet object contains all of the rows which satisfied the conditions in an SQL statement • A ResultSet object maintains a cursor pointing to its current row of data – Use next() to step through the result set row by row • next() returns TRUE if there are still remaining records – getString(), getInt(), and getXXX() assign each value to a Java variable Record 1 Record 2 Record 3 Record 4 ResultSetInternal Pointer The internal pointer starts one before the first record
  • 19. 19 ResultSet Example Statement stmt = con.createStatement(); ResultSet rs = stmt. executeQuery("select id,name from tbStudent"); // Print the result while(rs.next()) { System.out.print(rs.getInt(1) + ":"); System.out.println(rs.getString(“name")); }
  • 20. 20 ResultSet Meta-Data ResultSetMetaData rsmd = rs.getMetaData(); int numcols = rsmd.getColumnCount(); for (int i = 1 ; i <= numcols; i++) { System.out.print(rsmd.getColumnLabel(i)+" "); } A ResultSetMetaData is an object that can be used to get information about the properties of the columns in a ResultSet object An example: write the columns of the result set
  • 21. 21 Cleaning Up After Yourself • Remember to close the Connections, Statements, Prepared Statements and Result Sets con.close(); stmt.close(); pstmt.close(); rs.close()
  • 22. 22 Dealing With Exceptions • An SQLException is actually a list of exceptions catch (SQLException e) { while (e != null) { System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); e = e.getNextException(); } }
  • 23. 23 Transactions and JDBC • Transaction: more than one statement that must all succeed (or all fail) together – e.g., updating several tables due to customer purchase • If one fails, the system must reverse all previous actions • Also can’t leave DB in inconsistent state halfway through a transaction • COMMIT = complete transaction • ROLLBACK = cancel all actions
  • 24. 24 Example • Suppose we want to transfer money from bank account 13 to account 72: PreparedStatement pstmt = con.prepareStatement("update BankAccount set amount = amount + ? where accountId = ?"); pstmt.setInt(1,-100); pstmt.setInt(2, 13); pstmt.executeUpdate(); pstmt.setInt(1, 100); pstmt.setInt(2, 72); pstmt.executeUpdate(); What happens if this update fails?
  • 25. 25 Transaction Management • Transactions are not explicitly opened and closed • The connection has a state called AutoCommit mode • if AutoCommit is true, then every statement is automatically committed • if AutoCommit is false, then every statement is added to an ongoing transaction • Default: true
  • 26. 26 AutoCommit • If you set AutoCommit to false, you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback() • Note: DDL statements (e.g., creating/deleting tables) in a transaction may be ignored or may cause a commit to occur – The behavior is DBMS dependent setAutoCommit(boolean val)