SlideShare a Scribd company logo
3
Most read
6
Most read
12
Most read
JDBC Tutorial MIE456 -  Information Systems Infrastructure II Vinod Muthusamy November 4, 2004
Milestone 2 overview RMI ApptController interface given Write ApptControllerServer (implement ApptController) Write ApptControllerClient JDBC Write ApptRepositoryDB (extend ApptRepository) Must translate all calls to SQL statements GUI Server Database RMI JDBC
Java Database Connectivity (JDBC) An  interface  to communicate with a relational database Allows database agnostic Java code Treat database tables/rows/columns as Java objects JDBC driver An implementation of the JDBC interface Communicates with a particular database Database Database JDBC driver Java app Database JDBC calls Database commands JDBC driver JDBC driver
Eclipse JDBC setup Install driver Download MySQL JDBC driver from assignment Web page Unzip mysql-connector-xxx.jar Add mysql-connector-xxx.jar to Eclipse project Project    Properties    Java Build Path    Libraries    Add External JARs
JDBC steps Connect to database Query database (or insert/update/delete) Process results Close connection to database
1. Connect to database Load JDBC driver Class.forName(&quot;com.mysql.jdbc.Driver&quot;).newInstance(); Make connection Connection conn = DriverManager.getConnection(url); URL Format:  “jdbc:< subprotocol >:< subname >” jdbc:mysql://128.100.53.33/GROUPNUMBER?user=USER&password=PASSWORD
2. Query database Create statement Statement stmt = conn.createStatement(); stmt object sends SQL commands to database Methods executeQuery()  for SELECT statements executeUpdate()  for INSERT, UPDATE, DELETE, statements Send SQL statements stmt.executeQuery(“SELECT …”); stmt.executeUpdate(“INSERT …”);
3. Process results Result of a SELECT statement (rows/columns) returned as a  ResultSet  object ResultSet rs =    stmt.executeQuery(&quot;SELECT * FROM users&quot;); 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”); users table userid firstname lastname password type Bob Bob King cat 0 John John Smith pass 1
Print the users table ResultSet rs = stmt. executeQuery (&quot;SELECT * FROM users&quot;); 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
Add a row to the users table String str =  &quot;INSERT INTO users   VALUES('Bob', 'Bob', 'King',   'cat', 0)”; // Returns number of rows in table int rows = stmt.executeUpdate(str); users table userid firstname lastname password type Bob Bob King cat 0
4. Close connection to database Close the ResultSet object rs.close(); Close the Statement object stmt.close(); Close the connection conn.close();
import java.sql.*; public class Tester { public static void main(String[] args) { try { // Load JDBC driver Class.forName(&quot;com.mysql.jdbc.Driver&quot;).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(&quot;SELECT * FROM users&quot;); while (rs.next()) { ... } // Cleanup rs.close(); stmt.close(); conn.close(); } catch (Exception e) { System.out.println(&quot;exception &quot; + e); } }
Transactions Currently every executeUpdate() is “finalized” right away Sometimes want to a set of updates to all fail or all succeed E.g. add to Appointments and Bookings tables Treat both inserts as one transaction Transaction Used to group several SQL statements together Either all succeed or all fail
Transactions Commit Execute all statements as one unit “ Finalize” updates Rollback Abort transaction All uncommited statements are discarded Revert database to original state
Transactions in JDBC Disable auto-commit for the connection conn.setAutoCommit(false); Call necessary executeUpdate() statements Commit or rollback conn.commit(); conn.rollback();
References JDBC API Documentation http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/index.html Note: this is a newer JDBC API, but should be mostly compatible Some slide content borrowed from http://java.sun.com/docs/books/tutorial/jdbc/basics/index.html http://otn.oracle.co.kr/admin/seminar/data/otn-jdbc.ppt http://notes.corewebprogramming.com/student/JDBC.pdf
Ad

Recommended

CORBA.ppt
CORBA.ppt
rameshwarchintamani
 
Working with Databases and MySQL
Working with Databases and MySQL
Nicole Ryan
 
Java Networking
Java Networking
Sunil OS
 
Java rmi
Java rmi
kamal kotecha
 
Java Servlets
Java Servlets
BG Java EE Course
 
Set operators
Set operators
Manuel S. Enverga University Foundation
 
Delegates and events in C#
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
Procedures and triggers in SQL
Procedures and triggers in SQL
Vikash Sharma
 
Soap vs rest
Soap vs rest
Antonio Severien
 
SQL JOIN
SQL JOIN
Ritwik Das
 
Adbms 17 object query language
Adbms 17 object query language
Vaibhav Khanna
 
2. Distributed Systems Hardware & Software concepts
2. Distributed Systems Hardware & Software concepts
Prajakta Rane
 
STRUCTURE OF SQL QUERIES
STRUCTURE OF SQL QUERIES
VENNILAV6
 
J2 ee container & components
J2 ee container & components
Keshab Nath
 
What is AWS Cloud Watch
What is AWS Cloud Watch
jeetendra mandal
 
Enterprise Java Beans - EJB
Enterprise Java Beans - EJB
Peter R. Egli
 
Java Server Pages(jsp)
Java Server Pages(jsp)
Manisha Keim
 
Triggers and active database
Triggers and active database
BalaMuruganSamuthira
 
android sqlite
android sqlite
Deepa Rani
 
An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST
Ram Awadh Prasad, PMP
 
SQL Joins With Examples | Edureka
SQL Joins With Examples | Edureka
Edureka!
 
Database fragmentation
Database fragmentation
Punjab College Of Technical Education
 
basic structure of SQL FINAL.pptx
basic structure of SQL FINAL.pptx
Anusha sivakumar
 
Introduction to API
Introduction to API
rajnishjha29
 
Spring Data JPA
Spring Data JPA
Knoldus Inc.
 
enterprise java bean
enterprise java bean
Jitender Singh Lodhi
 
Java Server Pages
Java Server Pages
Kasun Madusanke
 
SQL Commands
SQL Commands
Sachidananda M H
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivity
Tanmoy Barman
 
Jdbc Ppt
Jdbc Ppt
Centre for Budget and Governance Accountability (CBGA)
 

More Related Content

What's hot (20)

Soap vs rest
Soap vs rest
Antonio Severien
 
SQL JOIN
SQL JOIN
Ritwik Das
 
Adbms 17 object query language
Adbms 17 object query language
Vaibhav Khanna
 
2. Distributed Systems Hardware & Software concepts
2. Distributed Systems Hardware & Software concepts
Prajakta Rane
 
STRUCTURE OF SQL QUERIES
STRUCTURE OF SQL QUERIES
VENNILAV6
 
J2 ee container & components
J2 ee container & components
Keshab Nath
 
What is AWS Cloud Watch
What is AWS Cloud Watch
jeetendra mandal
 
Enterprise Java Beans - EJB
Enterprise Java Beans - EJB
Peter R. Egli
 
Java Server Pages(jsp)
Java Server Pages(jsp)
Manisha Keim
 
Triggers and active database
Triggers and active database
BalaMuruganSamuthira
 
android sqlite
android sqlite
Deepa Rani
 
An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST
Ram Awadh Prasad, PMP
 
SQL Joins With Examples | Edureka
SQL Joins With Examples | Edureka
Edureka!
 
Database fragmentation
Database fragmentation
Punjab College Of Technical Education
 
basic structure of SQL FINAL.pptx
basic structure of SQL FINAL.pptx
Anusha sivakumar
 
Introduction to API
Introduction to API
rajnishjha29
 
Spring Data JPA
Spring Data JPA
Knoldus Inc.
 
enterprise java bean
enterprise java bean
Jitender Singh Lodhi
 
Java Server Pages
Java Server Pages
Kasun Madusanke
 
SQL Commands
SQL Commands
Sachidananda M H
 
Adbms 17 object query language
Adbms 17 object query language
Vaibhav Khanna
 
2. Distributed Systems Hardware & Software concepts
2. Distributed Systems Hardware & Software concepts
Prajakta Rane
 
STRUCTURE OF SQL QUERIES
STRUCTURE OF SQL QUERIES
VENNILAV6
 
J2 ee container & components
J2 ee container & components
Keshab Nath
 
Enterprise Java Beans - EJB
Enterprise Java Beans - EJB
Peter R. Egli
 
Java Server Pages(jsp)
Java Server Pages(jsp)
Manisha Keim
 
android sqlite
android sqlite
Deepa Rani
 
An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST
Ram Awadh Prasad, PMP
 
SQL Joins With Examples | Edureka
SQL Joins With Examples | Edureka
Edureka!
 
basic structure of SQL FINAL.pptx
basic structure of SQL FINAL.pptx
Anusha sivakumar
 
Introduction to API
Introduction to API
rajnishjha29
 

Viewers also liked (20)

JDBC: java DataBase connectivity
JDBC: java DataBase connectivity
Tanmoy Barman
 
Jdbc Ppt
Jdbc Ppt
Centre for Budget and Governance Accountability (CBGA)
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
kamal kotecha
 
JDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
Jdbc ppt
Jdbc ppt
Vikas Jagtap
 
JDBC Java Database Connectivity
JDBC Java Database Connectivity
Ranjan Kumar
 
Jdbc
Jdbc
Nitesh Kumar Pandey
 
Database Access With JDBC
Database Access With JDBC
Dharani Kumar Madduri
 
Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)
Som Prakash Rai
 
3 database-jdbc(1)
3 database-jdbc(1)
hameedkhan2017
 
Jdbc (database in java)
Jdbc (database in java)
Maher Abdo
 
Interface result set
Interface result set
myrajendra
 
Dacj 4 1-c
Dacj 4 1-c
Niit Care
 
Jdbc connectivity
Jdbc connectivity
arikazukito
 
Java session16
Java session16
Niit Care
 
Java.sql package
Java.sql package
myrajendra
 
JDBC
JDBC
Ankit Desai
 
Anchor data type,cursor data type,array data type
Anchor data type,cursor data type,array data type
dhruv patel
 
Jdbc
Jdbc
Jussi Pohjolainen
 
Ad

Similar to JDBC Tutorial (20)

JDBC.ppt
JDBC.ppt
Jayaprasanna4
 
jdbc
jdbc
vikram singh
 
Data Access with JDBC
Data Access with JDBC
BG Java EE Course
 
My sql with java
My sql with java
oly07104
 
Jdbc
Jdbc
smvdurajesh
 
Jdbc presentation
Jdbc presentation
nrjoshiee
 
Java JDBC
Java JDBC
Jussi Pohjolainen
 
Jdbc[1]
Jdbc[1]
Fulvio Corno
 
JDBC programming
JDBC programming
Fulvio Corno
 
JDBC
JDBC
Balwinder Kumar
 
Executing Sql Commands
Executing Sql Commands
phanleson
 
Executing Sql Commands
Executing Sql Commands
leminhvuong
 
KMUTNB - Internet Programming 6/7
KMUTNB - Internet Programming 6/7
phuphax
 
java4th.pdf bilgisayar mühendisliği bölümü
java4th.pdf bilgisayar mühendisliği bölümü
Smeyyeztrk10
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
Fulvio Corno
 
Database connect
Database connect
Yoga Raja
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)
Craig Dickson
 
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Core Java Programming Language (JSE) : Chapter XIII - JDBC
WebStackAcademy
 
Java 1-contd
Java 1-contd
Mukesh Tekwani
 
Jdbc
Jdbc
Indu Lata
 
My sql with java
My sql with java
oly07104
 
Jdbc presentation
Jdbc presentation
nrjoshiee
 
Executing Sql Commands
Executing Sql Commands
phanleson
 
Executing Sql Commands
Executing Sql Commands
leminhvuong
 
KMUTNB - Internet Programming 6/7
KMUTNB - Internet Programming 6/7
phuphax
 
java4th.pdf bilgisayar mühendisliği bölümü
java4th.pdf bilgisayar mühendisliği bölümü
Smeyyeztrk10
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
Fulvio Corno
 
Database connect
Database connect
Yoga Raja
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)
Craig Dickson
 
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Core Java Programming Language (JSE) : Chapter XIII - JDBC
WebStackAcademy
 
Ad

More from Information Technology (20)

Web303
Web303
Information Technology
 
Sql Server Security Best Practices
Sql Server Security Best Practices
Information Technology
 
SAN
SAN
Information Technology
 
SAN Review
SAN Review
Information Technology
 
SQL 2005 Disk IO Performance
SQL 2005 Disk IO Performance
Information Technology
 
RAID Review
RAID Review
Information Technology
 
Review of SQL
Review of SQL
Information Technology
 
Sql 2005 high availability
Sql 2005 high availability
Information Technology
 
IIS 7: The Administrator’s Guide
IIS 7: The Administrator’s Guide
Information Technology
 
MOSS 2007 Deployment Fundamentals -Part2
MOSS 2007 Deployment Fundamentals -Part2
Information Technology
 
MOSS 2007 Deployment Fundamentals -Part1
MOSS 2007 Deployment Fundamentals -Part1
Information Technology
 
Clustering and High Availability
Clustering and High Availability
Information Technology
 
F5 beyond load balancer (nov 2009)
F5 beyond load balancer (nov 2009)
Information Technology
 
WSS 3.0 & SharePoint 2007
WSS 3.0 & SharePoint 2007
Information Technology
 
SharePoint Topology
SharePoint Topology
Information Technology
 
Sharepoint Deployments
Sharepoint Deployments
Information Technology
 
Microsoft Clustering
Microsoft Clustering
Information Technology
 
Scalable Internet Servers and Load Balancing
Scalable Internet Servers and Load Balancing
Information Technology
 
Web Hacking
Web Hacking
Information Technology
 
Migration from ASP to ASP.NET
Migration from ASP to ASP.NET
Information Technology
 

Recently uploaded (20)

“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
Edge AI and Vision Alliance
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
Edge AI and Vision Alliance
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Data Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
Edge AI and Vision Alliance
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
Edge AI and Vision Alliance
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Data Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 

JDBC Tutorial

  • 1. JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004
  • 2. Milestone 2 overview RMI ApptController interface given Write ApptControllerServer (implement ApptController) Write ApptControllerClient JDBC Write ApptRepositoryDB (extend ApptRepository) Must translate all calls to SQL statements GUI Server Database RMI JDBC
  • 3. Java Database Connectivity (JDBC) An interface to communicate with a relational database Allows database agnostic Java code Treat database tables/rows/columns as Java objects JDBC driver An implementation of the JDBC interface Communicates with a particular database Database Database JDBC driver Java app Database JDBC calls Database commands JDBC driver JDBC driver
  • 4. Eclipse JDBC setup Install driver Download MySQL JDBC driver from assignment Web page Unzip mysql-connector-xxx.jar Add mysql-connector-xxx.jar to Eclipse project Project  Properties  Java Build Path  Libraries  Add External JARs
  • 5. JDBC steps Connect to database Query database (or insert/update/delete) Process results Close connection to database
  • 6. 1. Connect to database Load JDBC driver Class.forName(&quot;com.mysql.jdbc.Driver&quot;).newInstance(); Make connection Connection conn = DriverManager.getConnection(url); URL Format: “jdbc:< subprotocol >:< subname >” jdbc:mysql://128.100.53.33/GROUPNUMBER?user=USER&password=PASSWORD
  • 7. 2. Query database Create statement Statement stmt = conn.createStatement(); stmt object sends SQL commands to database Methods executeQuery() for SELECT statements executeUpdate() for INSERT, UPDATE, DELETE, statements Send SQL statements stmt.executeQuery(“SELECT …”); stmt.executeUpdate(“INSERT …”);
  • 8. 3. Process results Result of a SELECT statement (rows/columns) returned as a ResultSet object ResultSet rs = stmt.executeQuery(&quot;SELECT * FROM users&quot;); 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”); users table userid firstname lastname password type Bob Bob King cat 0 John John Smith pass 1
  • 9. Print the users table ResultSet rs = stmt. executeQuery (&quot;SELECT * FROM users&quot;); 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
  • 10. Add a row to the users table String str = &quot;INSERT INTO users VALUES('Bob', 'Bob', 'King', 'cat', 0)”; // Returns number of rows in table int rows = stmt.executeUpdate(str); users table userid firstname lastname password type Bob Bob King cat 0
  • 11. 4. Close connection to database Close the ResultSet object rs.close(); Close the Statement object stmt.close(); Close the connection conn.close();
  • 12. import java.sql.*; public class Tester { public static void main(String[] args) { try { // Load JDBC driver Class.forName(&quot;com.mysql.jdbc.Driver&quot;).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(&quot;SELECT * FROM users&quot;); while (rs.next()) { ... } // Cleanup rs.close(); stmt.close(); conn.close(); } catch (Exception e) { System.out.println(&quot;exception &quot; + e); } }
  • 13. Transactions Currently every executeUpdate() is “finalized” right away Sometimes want to a set of updates to all fail or all succeed E.g. add to Appointments and Bookings tables Treat both inserts as one transaction Transaction Used to group several SQL statements together Either all succeed or all fail
  • 14. Transactions Commit Execute all statements as one unit “ Finalize” updates Rollback Abort transaction All uncommited statements are discarded Revert database to original state
  • 15. Transactions in JDBC Disable auto-commit for the connection conn.setAutoCommit(false); Call necessary executeUpdate() statements Commit or rollback conn.commit(); conn.rollback();
  • 16. References JDBC API Documentation http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/index.html Note: this is a newer JDBC API, but should be mostly compatible Some slide content borrowed from http://java.sun.com/docs/books/tutorial/jdbc/basics/index.html http://otn.oracle.co.kr/admin/seminar/data/otn-jdbc.ppt http://notes.corewebprogramming.com/student/JDBC.pdf