SlideShare uma empresa Scribd logo
1 de 35
Baixar para ler offline
Java Database Connectivity
(JDBC)
By Laxmi Edi
M.Tech (Ph.D)
Introduction
•Database
Collection of data
•DBMS
Database management system
Storing and organizing data
•SQL
Relational database
Structured Query Language
•JDBC
Java Database Connectivity
JDBC driver
www.kerneltraining.com
JDBC
Programsdeveloped with Java/JDBCare platform and vendor
independent.
“writeonce, compile once, run anywhere”
Write apps in java to access any DB, using standardSQL statements –
while still followingJava conventions.
JDBC driver manager and JDBC drivers providethe bridge between the
databaseand java worlds.
www.kerneltraining.com
Java application
JDBC Driver Manager
JDBC/ODBC
Bridge
vendor-
supplied
JDBC driver
ODBC
driver
DatabaseDatabase
JDBC API
JDBC Driver API
www.kerneltraining.com
JDBC Components
www.kerneltraining.com
ODBC
•JDBC heavily influenced by ODBC
•ODBC provides a C interface for database access on
Windows environment.
•ODBC has a few commands with lots of complex options.
Java prefers simple methods but lots of them.
www.kerneltraining.com
JDBC Driver Types
www.kerneltraining.com
Relational-Database Model
• Relational database
Table
Record
Field, column
Primarykey
•Unique data
• SQL statement
Query
Record sets
www.kerneltraining.com
Structured Query Language (SQL)
• SQL overview
• SQL keywords
SQL keyword Description
SELECT Select (retrieve) fields from one or more tables.
FROM Tables from which to get fields. Required in every SELECT.
WHERE Criteria for selection that determine the rows to be retrieved.
GROUP BY Criteria for grouping records.
ORDER BY Criteria for ordering records.
INSERT INTO Insert data into a specified table.
UPDATE Update data in a specified table.
DELETE FROM Delete data from a specified table.
Fig. 8.12 SQL query keywords.
www.kerneltraining.com
Basic SELECT Query
• Simplest format of a SELECT query
SELECT * FROM tableName
SELECT * FROM authors
• Select specific fields from a table
SELECT authorID, lastName FROM authors
authorID lastName
1 Deitel
2 Deitel
3 Nieto
4 Santry
Fig. 8.13 authorID and lastName from the authors table.
www.kerneltraining.com
WHERE Clause
• Specify the selection criteria
SELECT fieldName1, fieldName2, … FROM tableName WHERE criteria
SELECT title, editionNumber, copyright
FROM titles
WHERE copyright > 1999
• WHERE clause condition operators
- <, >, <=, >=, =, <>
- LIKE
•wildcard characters % and _
www.kerneltraining.com
WHERE Clause (Cont.)
• SELECT authorID, firstName, lastName
FROM authors
WHERE lastName LIKE ‘D%’
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
Fig. 8.15 Authors whose last name starts with D from the authors table.
www.kerneltraining.com
WHERE Clause (Cont.)
• SELECT authorID, firstName, lastName
FROM authors
WHERE lastName LIKE ‘_i%’
authorID firstName lastName
3 Tem Nieto
Fig. 8.16 The only author from the authors table whose last name
contains i as the second letter.
www.kerneltraining.com
ORDER BY Clause
• Optional ORDER BY clause
SELECT fieldName1, fieldName2, … FROM tableName ORDER BY field ASC
SELECT fieldName1, fieldName2, … FROM tableName ORDER BY field DESC
• ORDER BY multiple fields
ORDER BY field1 sortingOrder, field2 sortingOrder, …
• Combine the WHERE and ORDER BY clauses
www.kerneltraining.com
ORDER BY Clause (Cont.)
• SELECT authorID, firstName, lastName
FROM authors
ORDER BY lastName ASC
authorID firstName lastName
2 Paul Deitel
1 Harvey Deitel
3 Tem Nieto
4 Sean Santry
Fig. 8.17 Authors from table authors in ascending order by lastName.
www.kerneltraining.com
ORDER BY Clause (Cont.)
• SELECT authorID, firstName, lastName
FROM authors
ORDER BY lastName DESC
authorID firstName lastName
4 Sean Santry
3 Tem Nieto
2 Paul Deitel
1 Harvey Deitel
Fig. 8.18 Authors from table authors in descending order by lastName.
www.kerneltraining.com
ORDER BY Clause (Cont.)
• SELECT authorID, firstName, lastName
FROM authors
ORDER BY lastName, firstName
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
3 Tem Nieto
4 Sean Santry
Fig. 8.19 Authors from table authors in ascending order by lastName
and by firstName.
www.kerneltraining.com
ORDER BY Clause (Cont.)
•SELECT isbn, title, editionNumber, copyright, price
FROM titles WHERE title LIKE ‘%How to Program’
ORDER BY title ASC
isbn title edition-
Number
copy-
right
price
0130895601 Advanced Java 2 Platform How to Program 1 2002 69.95
0132261197 C How to Program 2 1994 49.95
0130895725 C How to Program 3 2001 69.95
0135289106 C++ How to Program 2 1998 49.95
0130895717 C++ How to Program 3 2001 69.95
0130161438 Internet and World Wide Web How to
Program
1 2000 69.95
0130284181 Perl How to Program 1 2001 69.95
0134569555 Visual Basic 6 How to Program 1 1999 69.95
0130284173 XML How to Program 1 2001 69.95
013028419x e-Business and e-Commerce How to
Program
1 2001 69.95
Fig. 8.20 Books from table titles whose title ends with How to Program in
ascending order by title.
www.kerneltraining.com
Merging Data from Multiple Tables: Joining
•Join the tables
-Merge data from multiple tables into a single view
- SELECT fieldName1, fieldName2, …
FROM table1, table2
WHERE table1.fieldName = table2.fieldName
- SELECT firstName, lastName, isbn
FROM authors, authorISBN
WHERE authors.authorID = authorISBN.authorID
ORDER BY lastName, firstName
www.kerneltraining.com
INSERT INTO Statement
• Insert a new record into a table
INSERT INTO tableName ( fieldName1, … , fieldNameN )
VALUES ( value1, … , valueN )
INSERT INTO authors ( firstName, lastName )
VALUES ( ‘Sue’, ‘Smith’ )
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
3 Tem Nieto
4 Sean Santry
5 Sue Smith
Fig. 8.22 Table Authors after an INSERT INTO operation to add a record.
www.kerneltraining.com
UPDATE Statement
• Modify data in a table
UPDATE tableName
SET fieldName1 = value1, … , fieldNameN = valueN
WHERE criteria
• UPDATE authors
SET lastName = ‘Jones’
WHERE lastName = ‘Smith’ AND firstName = ‘Sue’
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
3 Tem Nieto
4 Sean Santry
5 Sue Jones
Fig. 8.23 Table authors after an UPDATE operation to change a record.
www.kerneltraining.com
DELETE FROM Statement
•Remove data from a table
- DELETE FROM tableName WHERE criteria
• DELETE FROM authors
WHERE lastName = ‘Jones’ AND firstName = ‘Sue’
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
3 Tem Nieto
4 Sean Santry
Fig. 8.24 Table authors after a DELETE operation to remove a record.
www.kerneltraining.com
Database Programming Steps
1. Establish a connection
2. Begin transaction
3. Create a statement object
4. Associate SQL with the statement object
5. Provide values for statement parameters
6. Execute the statement object
7. Process the results
8. End transaction
9. Release resources
www.kerneltraining.com
Using JDBC
1a. Load the driver:
- The driver class librariesneed to be in the CLASSPATH for the Java
compiler and for the Java virtual machine.
- The most reliable way to load the driver into the program is:
Class.forName(string).newInstance();
1b. Establish a connection to the database:
- A connectionURL string includes the literal jdbc:, followed by the
name of the driver and a URL to the database
String url =
"jdbc:oracle:thin:@reddwarf.cs.rit.edu:1521:csodb";
jdbc “subprotocol”“subname” host port database
- Create a Connection object:
Connection con = DriverManager.getConnection(url,
dbUser, dbPassword);
www.kerneltraining.com
Using JDBC (Continued)
2. Begin the transaction
con.setTransactionIsolation(
Connection.TRANSACTION_SERIALIZABLE );
con.setAutoCommit( false );
3. Createa statement object
Statement stmt = conn.createStatement();
4. Associate SQL with the statement object
String queryString = "create table students "
+ "(name varchar(30), id int, phone char(9))";
6. Process the statement:
Example statements:
ResultSet rs = stmt.executeQuery(querystring);
int result = stmt.executeUpdate(updatestring);
ResultSetMetaData rsMeta = rs.getMetaData();
• Compiled queries can be processed via a PreparedStatementobject
• Stored procedures can be processed via a CallableStatementobject
www.kerneltraining.com
Using JDBC (Continued)
8. End transaction
con.commit();
con.rollback();
9. Release resources
con.close();
www.kerneltraining.com
JDBC Classes for DB Connection
•java.sql.Driver
-Unless creating custom JDBC implementation, never have to deal with it.
It gives JDBC a launching point for DB connectivity by responding to
DriverManager connection requests
•java.sql.DriverManager
- Maintains a list of Driver implementations and presents an application
with one that matches a requested URL.
getConnection(url, uid, password)
getDrivers(), registerDriver()
•java.sql.Connection
- Represents a single logical DB connection; used for sending SQL
statements
www.kerneltraining.com
Database URLs
•Uses syntax similar to net URLs
- jdbc:odbc:CoreJava
-jdbc:pointbase:CATS
•General syntax
- jdbc:subprotocol_name:other_stuff
- Where subprotocol selects the specific driver
- Format for other_stuff depends on subprotocol, but in general:
- jdbc:subprotocol://hostname:port/other
- jdbc:odbc://whitehouse.gov:5000/CATS;PWD=Rice would
connect to the CATS DB on port 5000 of whitehouse.gov, using the
ODBC attribute value of PWD set to “Rice”.
www.kerneltraining.com
JDBC – Making the Connection
• Register the Driver implementation of the DB. JDBC requires a
Driver class to register itself with DriverManager when it is
instantiated.
- Explicitly call new to load the driver (needs to be hardcoded)
- Or, use Class.forName(“DriverClass”)
• Establish a connection with the DB
Connection c = DriverManager.getConnection(url,
uid, password);
- DM searches the registered Drivers until it finds the match.
- The Driver class then establishes the connection, returns a
connection object to DM, which in turn returns it back.
www.kerneltraining.com
JDBC – Database Access Classes
•java.sql.Statement
- Most basic class. It performs all the SQL statements
- executeQuery( String ), executeUpdate( String
), execute( String )
•java.sql.ResultSet
- One or more rows of data returned by a query
Statement st = c.createStatement();
ResultSet rs = st.executeQuery(“…”);
- Methods: next(),getString(column),getInt(..),
last(), getRow()
- Be careful about SQL NULL and Java NULL
- Always use wasNull()
- Always call close() on all ResultSet, Statement, and
Connection objects. Some drivers (e.g., IBM’s nativeDB2) will
not close the rs and st objects even when you close the connection.
www.kerneltraining.com
JDBC – DB Access Classes (Cont.)
•java.sql.ResultSetMetaData
- Provides extra informationabout (data about data)the ResultSet
object
- getColumnCount(), getColumnName(column)
ResultSetMetaData md = rs.getMetaData();
•java.sql.DatabaseMetaData
- Provides extra informationabout the databasefor a given
connectionobject
- What tables exist, what username is being used, is the DB read-
only, what are the primarykeys for a table, etc.
DatabaseMetaData dmd = c.getMetaData();
- Lets developerswrite apps that are DB-independent
www.kerneltraining.com
Prepared SQL
• For each SQL statement received, the DB builds a query plan by
- parsing the SQL statement
- readingthe SQL to determine what to do
-formulatinga plan for executing the SQL
• RepeatedlyexecutingSQL with same query plan is very inefficient
- UPDATE account SET balance = XXX WHERE id = YYY
Statement st = c.createStatement();
for (int i=0; i<accounts.length; i++ )
st.executeUpdate(“UPDATE account “ +
“SET balance = “ +
accounts[i].getBalance() +
“WHERE id = “ + accounts[i].getId());
www.kerneltraining.com
Prepared SQL (contd.)
• DBs enableyou to optimize repeated calls through prepared SQL.
• Createa Java instance of a prepared statement that notifies the DB of
the kind of SQL call it represents.
• DB can then createa query plan for that SQL even before it is actually
executed.
• If the same prepared statement is executed more than once, the DB
uses the same query plan without rebuildinga new one.
www.kerneltraining.com
Prepared SQL (contd.)
// create SQL statement with parameters
PreparedStatement st = c.prepareStatement(
“UPDATE account “ +
“SET balance = ? “ +
“WHERE id = ?”);
for (int i=0; i<accounts.length; i++) {
// bind the parameters
st.setFloat(1, accounts[i].getBalance());
st.setInt(2, accounts[i].getId());
st.execute();
st.clearParameters();
}
www.kerneltraining.com
THANK YOU
for attending Introduction to
Java Database Connectivity
(JDBC)
www.kerneltraining.com

Mais conteúdo relacionado

Destaque

Overview of v cloud case studies
Overview of v cloud case studiesOverview of v cloud case studies
Overview of v cloud case studiessolarisyougood
 
Avoiding Chaos: Methodology for Managing Performance in a Shared Storage A...
Avoiding Chaos:  Methodology for Managing Performance in a Shared Storage A...Avoiding Chaos:  Methodology for Managing Performance in a Shared Storage A...
Avoiding Chaos: Methodology for Managing Performance in a Shared Storage A...brettallison
 
Presentation oracle on power power advantages and license optimization
Presentation   oracle on power power advantages and license optimizationPresentation   oracle on power power advantages and license optimization
Presentation oracle on power power advantages and license optimizationsolarisyougood
 
Visual studio 2008 overview
Visual studio 2008 overviewVisual studio 2008 overview
Visual studio 2008 overviewsagaroceanic11
 
Aix admin course provider Navi Mumbai | AIX Admin Course Training Navi Mumbai...
Aix admin course provider Navi Mumbai | AIX Admin Course Training Navi Mumbai...Aix admin course provider Navi Mumbai | AIX Admin Course Training Navi Mumbai...
Aix admin course provider Navi Mumbai | AIX Admin Course Training Navi Mumbai...VibrantGroup
 
Proof of concept guide for ibm tivoli storage manager version 5.3 sg246762
Proof of concept guide for ibm tivoli storage manager version 5.3 sg246762Proof of concept guide for ibm tivoli storage manager version 5.3 sg246762
Proof of concept guide for ibm tivoli storage manager version 5.3 sg246762Banking at Ho Chi Minh city
 
Ibm tivoli storage manager bare machine recovery for aix with sysback - red...
Ibm tivoli storage manager   bare machine recovery for aix with sysback - red...Ibm tivoli storage manager   bare machine recovery for aix with sysback - red...
Ibm tivoli storage manager bare machine recovery for aix with sysback - red...Banking at Ho Chi Minh city
 
Ibm tivoli storage manager in a clustered environment sg246679
Ibm tivoli storage manager in a clustered environment sg246679Ibm tivoli storage manager in a clustered environment sg246679
Ibm tivoli storage manager in a clustered environment sg246679Banking at Ho Chi Minh city
 
2.ibm flex system manager overview
2.ibm flex system manager overview2.ibm flex system manager overview
2.ibm flex system manager overviewsolarisyougood
 

Destaque (12)

AIX 5L Differences Guide Version 5.3 Edition
AIX 5L Differences Guide Version 5.3 EditionAIX 5L Differences Guide Version 5.3 Edition
AIX 5L Differences Guide Version 5.3 Edition
 
Overview of v cloud case studies
Overview of v cloud case studiesOverview of v cloud case studies
Overview of v cloud case studies
 
Avoiding Chaos: Methodology for Managing Performance in a Shared Storage A...
Avoiding Chaos:  Methodology for Managing Performance in a Shared Storage A...Avoiding Chaos:  Methodology for Managing Performance in a Shared Storage A...
Avoiding Chaos: Methodology for Managing Performance in a Shared Storage A...
 
Presentation oracle on power power advantages and license optimization
Presentation   oracle on power power advantages and license optimizationPresentation   oracle on power power advantages and license optimization
Presentation oracle on power power advantages and license optimization
 
Visual studio 2008 overview
Visual studio 2008 overviewVisual studio 2008 overview
Visual studio 2008 overview
 
Aix admin course provider Navi Mumbai | AIX Admin Course Training Navi Mumbai...
Aix admin course provider Navi Mumbai | AIX Admin Course Training Navi Mumbai...Aix admin course provider Navi Mumbai | AIX Admin Course Training Navi Mumbai...
Aix admin course provider Navi Mumbai | AIX Admin Course Training Navi Mumbai...
 
Proof of concept guide for ibm tivoli storage manager version 5.3 sg246762
Proof of concept guide for ibm tivoli storage manager version 5.3 sg246762Proof of concept guide for ibm tivoli storage manager version 5.3 sg246762
Proof of concept guide for ibm tivoli storage manager version 5.3 sg246762
 
Accelerate Return on Data
Accelerate Return on DataAccelerate Return on Data
Accelerate Return on Data
 
Ibm tivoli storage manager bare machine recovery for aix with sysback - red...
Ibm tivoli storage manager   bare machine recovery for aix with sysback - red...Ibm tivoli storage manager   bare machine recovery for aix with sysback - red...
Ibm tivoli storage manager bare machine recovery for aix with sysback - red...
 
IBMRedbook
IBMRedbookIBMRedbook
IBMRedbook
 
Ibm tivoli storage manager in a clustered environment sg246679
Ibm tivoli storage manager in a clustered environment sg246679Ibm tivoli storage manager in a clustered environment sg246679
Ibm tivoli storage manager in a clustered environment sg246679
 
2.ibm flex system manager overview
2.ibm flex system manager overview2.ibm flex system manager overview
2.ibm flex system manager overview
 

An Introduction to Java Database Conenctivity

  • 1. Java Database Connectivity (JDBC) By Laxmi Edi M.Tech (Ph.D)
  • 2. Introduction •Database Collection of data •DBMS Database management system Storing and organizing data •SQL Relational database Structured Query Language •JDBC Java Database Connectivity JDBC driver www.kerneltraining.com
  • 3. JDBC Programsdeveloped with Java/JDBCare platform and vendor independent. “writeonce, compile once, run anywhere” Write apps in java to access any DB, using standardSQL statements – while still followingJava conventions. JDBC driver manager and JDBC drivers providethe bridge between the databaseand java worlds. www.kerneltraining.com
  • 4. Java application JDBC Driver Manager JDBC/ODBC Bridge vendor- supplied JDBC driver ODBC driver DatabaseDatabase JDBC API JDBC Driver API www.kerneltraining.com
  • 6. ODBC •JDBC heavily influenced by ODBC •ODBC provides a C interface for database access on Windows environment. •ODBC has a few commands with lots of complex options. Java prefers simple methods but lots of them. www.kerneltraining.com
  • 8. Relational-Database Model • Relational database Table Record Field, column Primarykey •Unique data • SQL statement Query Record sets www.kerneltraining.com
  • 9. Structured Query Language (SQL) • SQL overview • SQL keywords SQL keyword Description SELECT Select (retrieve) fields from one or more tables. FROM Tables from which to get fields. Required in every SELECT. WHERE Criteria for selection that determine the rows to be retrieved. GROUP BY Criteria for grouping records. ORDER BY Criteria for ordering records. INSERT INTO Insert data into a specified table. UPDATE Update data in a specified table. DELETE FROM Delete data from a specified table. Fig. 8.12 SQL query keywords. www.kerneltraining.com
  • 10. Basic SELECT Query • Simplest format of a SELECT query SELECT * FROM tableName SELECT * FROM authors • Select specific fields from a table SELECT authorID, lastName FROM authors authorID lastName 1 Deitel 2 Deitel 3 Nieto 4 Santry Fig. 8.13 authorID and lastName from the authors table. www.kerneltraining.com
  • 11. WHERE Clause • Specify the selection criteria SELECT fieldName1, fieldName2, … FROM tableName WHERE criteria SELECT title, editionNumber, copyright FROM titles WHERE copyright > 1999 • WHERE clause condition operators - <, >, <=, >=, =, <> - LIKE •wildcard characters % and _ www.kerneltraining.com
  • 12. WHERE Clause (Cont.) • SELECT authorID, firstName, lastName FROM authors WHERE lastName LIKE ‘D%’ authorID firstName lastName 1 Harvey Deitel 2 Paul Deitel Fig. 8.15 Authors whose last name starts with D from the authors table. www.kerneltraining.com
  • 13. WHERE Clause (Cont.) • SELECT authorID, firstName, lastName FROM authors WHERE lastName LIKE ‘_i%’ authorID firstName lastName 3 Tem Nieto Fig. 8.16 The only author from the authors table whose last name contains i as the second letter. www.kerneltraining.com
  • 14. ORDER BY Clause • Optional ORDER BY clause SELECT fieldName1, fieldName2, … FROM tableName ORDER BY field ASC SELECT fieldName1, fieldName2, … FROM tableName ORDER BY field DESC • ORDER BY multiple fields ORDER BY field1 sortingOrder, field2 sortingOrder, … • Combine the WHERE and ORDER BY clauses www.kerneltraining.com
  • 15. ORDER BY Clause (Cont.) • SELECT authorID, firstName, lastName FROM authors ORDER BY lastName ASC authorID firstName lastName 2 Paul Deitel 1 Harvey Deitel 3 Tem Nieto 4 Sean Santry Fig. 8.17 Authors from table authors in ascending order by lastName. www.kerneltraining.com
  • 16. ORDER BY Clause (Cont.) • SELECT authorID, firstName, lastName FROM authors ORDER BY lastName DESC authorID firstName lastName 4 Sean Santry 3 Tem Nieto 2 Paul Deitel 1 Harvey Deitel Fig. 8.18 Authors from table authors in descending order by lastName. www.kerneltraining.com
  • 17. ORDER BY Clause (Cont.) • SELECT authorID, firstName, lastName FROM authors ORDER BY lastName, firstName authorID firstName lastName 1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry Fig. 8.19 Authors from table authors in ascending order by lastName and by firstName. www.kerneltraining.com
  • 18. ORDER BY Clause (Cont.) •SELECT isbn, title, editionNumber, copyright, price FROM titles WHERE title LIKE ‘%How to Program’ ORDER BY title ASC isbn title edition- Number copy- right price 0130895601 Advanced Java 2 Platform How to Program 1 2002 69.95 0132261197 C How to Program 2 1994 49.95 0130895725 C How to Program 3 2001 69.95 0135289106 C++ How to Program 2 1998 49.95 0130895717 C++ How to Program 3 2001 69.95 0130161438 Internet and World Wide Web How to Program 1 2000 69.95 0130284181 Perl How to Program 1 2001 69.95 0134569555 Visual Basic 6 How to Program 1 1999 69.95 0130284173 XML How to Program 1 2001 69.95 013028419x e-Business and e-Commerce How to Program 1 2001 69.95 Fig. 8.20 Books from table titles whose title ends with How to Program in ascending order by title. www.kerneltraining.com
  • 19. Merging Data from Multiple Tables: Joining •Join the tables -Merge data from multiple tables into a single view - SELECT fieldName1, fieldName2, … FROM table1, table2 WHERE table1.fieldName = table2.fieldName - SELECT firstName, lastName, isbn FROM authors, authorISBN WHERE authors.authorID = authorISBN.authorID ORDER BY lastName, firstName www.kerneltraining.com
  • 20. INSERT INTO Statement • Insert a new record into a table INSERT INTO tableName ( fieldName1, … , fieldNameN ) VALUES ( value1, … , valueN ) INSERT INTO authors ( firstName, lastName ) VALUES ( ‘Sue’, ‘Smith’ ) authorID firstName lastName 1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry 5 Sue Smith Fig. 8.22 Table Authors after an INSERT INTO operation to add a record. www.kerneltraining.com
  • 21. UPDATE Statement • Modify data in a table UPDATE tableName SET fieldName1 = value1, … , fieldNameN = valueN WHERE criteria • UPDATE authors SET lastName = ‘Jones’ WHERE lastName = ‘Smith’ AND firstName = ‘Sue’ authorID firstName lastName 1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry 5 Sue Jones Fig. 8.23 Table authors after an UPDATE operation to change a record. www.kerneltraining.com
  • 22. DELETE FROM Statement •Remove data from a table - DELETE FROM tableName WHERE criteria • DELETE FROM authors WHERE lastName = ‘Jones’ AND firstName = ‘Sue’ authorID firstName lastName 1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry Fig. 8.24 Table authors after a DELETE operation to remove a record. www.kerneltraining.com
  • 23. Database Programming Steps 1. Establish a connection 2. Begin transaction 3. Create a statement object 4. Associate SQL with the statement object 5. Provide values for statement parameters 6. Execute the statement object 7. Process the results 8. End transaction 9. Release resources www.kerneltraining.com
  • 24. Using JDBC 1a. Load the driver: - The driver class librariesneed to be in the CLASSPATH for the Java compiler and for the Java virtual machine. - The most reliable way to load the driver into the program is: Class.forName(string).newInstance(); 1b. Establish a connection to the database: - A connectionURL string includes the literal jdbc:, followed by the name of the driver and a URL to the database String url = "jdbc:oracle:thin:@reddwarf.cs.rit.edu:1521:csodb"; jdbc “subprotocol”“subname” host port database - Create a Connection object: Connection con = DriverManager.getConnection(url, dbUser, dbPassword); www.kerneltraining.com
  • 25. Using JDBC (Continued) 2. Begin the transaction con.setTransactionIsolation( Connection.TRANSACTION_SERIALIZABLE ); con.setAutoCommit( false ); 3. Createa statement object Statement stmt = conn.createStatement(); 4. Associate SQL with the statement object String queryString = "create table students " + "(name varchar(30), id int, phone char(9))"; 6. Process the statement: Example statements: ResultSet rs = stmt.executeQuery(querystring); int result = stmt.executeUpdate(updatestring); ResultSetMetaData rsMeta = rs.getMetaData(); • Compiled queries can be processed via a PreparedStatementobject • Stored procedures can be processed via a CallableStatementobject www.kerneltraining.com
  • 26. Using JDBC (Continued) 8. End transaction con.commit(); con.rollback(); 9. Release resources con.close(); www.kerneltraining.com
  • 27. JDBC Classes for DB Connection •java.sql.Driver -Unless creating custom JDBC implementation, never have to deal with it. It gives JDBC a launching point for DB connectivity by responding to DriverManager connection requests •java.sql.DriverManager - Maintains a list of Driver implementations and presents an application with one that matches a requested URL. getConnection(url, uid, password) getDrivers(), registerDriver() •java.sql.Connection - Represents a single logical DB connection; used for sending SQL statements www.kerneltraining.com
  • 28. Database URLs •Uses syntax similar to net URLs - jdbc:odbc:CoreJava -jdbc:pointbase:CATS •General syntax - jdbc:subprotocol_name:other_stuff - Where subprotocol selects the specific driver - Format for other_stuff depends on subprotocol, but in general: - jdbc:subprotocol://hostname:port/other - jdbc:odbc://whitehouse.gov:5000/CATS;PWD=Rice would connect to the CATS DB on port 5000 of whitehouse.gov, using the ODBC attribute value of PWD set to “Rice”. www.kerneltraining.com
  • 29. JDBC – Making the Connection • Register the Driver implementation of the DB. JDBC requires a Driver class to register itself with DriverManager when it is instantiated. - Explicitly call new to load the driver (needs to be hardcoded) - Or, use Class.forName(“DriverClass”) • Establish a connection with the DB Connection c = DriverManager.getConnection(url, uid, password); - DM searches the registered Drivers until it finds the match. - The Driver class then establishes the connection, returns a connection object to DM, which in turn returns it back. www.kerneltraining.com
  • 30. JDBC – Database Access Classes •java.sql.Statement - Most basic class. It performs all the SQL statements - executeQuery( String ), executeUpdate( String ), execute( String ) •java.sql.ResultSet - One or more rows of data returned by a query Statement st = c.createStatement(); ResultSet rs = st.executeQuery(“…”); - Methods: next(),getString(column),getInt(..), last(), getRow() - Be careful about SQL NULL and Java NULL - Always use wasNull() - Always call close() on all ResultSet, Statement, and Connection objects. Some drivers (e.g., IBM’s nativeDB2) will not close the rs and st objects even when you close the connection. www.kerneltraining.com
  • 31. JDBC – DB Access Classes (Cont.) •java.sql.ResultSetMetaData - Provides extra informationabout (data about data)the ResultSet object - getColumnCount(), getColumnName(column) ResultSetMetaData md = rs.getMetaData(); •java.sql.DatabaseMetaData - Provides extra informationabout the databasefor a given connectionobject - What tables exist, what username is being used, is the DB read- only, what are the primarykeys for a table, etc. DatabaseMetaData dmd = c.getMetaData(); - Lets developerswrite apps that are DB-independent www.kerneltraining.com
  • 32. Prepared SQL • For each SQL statement received, the DB builds a query plan by - parsing the SQL statement - readingthe SQL to determine what to do -formulatinga plan for executing the SQL • RepeatedlyexecutingSQL with same query plan is very inefficient - UPDATE account SET balance = XXX WHERE id = YYY Statement st = c.createStatement(); for (int i=0; i<accounts.length; i++ ) st.executeUpdate(“UPDATE account “ + “SET balance = “ + accounts[i].getBalance() + “WHERE id = “ + accounts[i].getId()); www.kerneltraining.com
  • 33. Prepared SQL (contd.) • DBs enableyou to optimize repeated calls through prepared SQL. • Createa Java instance of a prepared statement that notifies the DB of the kind of SQL call it represents. • DB can then createa query plan for that SQL even before it is actually executed. • If the same prepared statement is executed more than once, the DB uses the same query plan without rebuildinga new one. www.kerneltraining.com
  • 34. Prepared SQL (contd.) // create SQL statement with parameters PreparedStatement st = c.prepareStatement( “UPDATE account “ + “SET balance = ? “ + “WHERE id = ?”); for (int i=0; i<accounts.length; i++) { // bind the parameters st.setFloat(1, accounts[i].getBalance()); st.setInt(2, accounts[i].getId()); st.execute(); st.clearParameters(); } www.kerneltraining.com
  • 35. THANK YOU for attending Introduction to Java Database Connectivity (JDBC) www.kerneltraining.com