SlideShare a Scribd company logo
1 of 34
L10. Java Database Connectivity
with JDBC
ECE
318
-
Programming
Principles
for
Engineers.
What is a database?
ECE
318
-
Programming
Principles
for
Engineers.
Introduction
DataBase Management System (DBMS)
● Mechanisms for storing and organizing data
● Access, store, modify data without concern for internal representation (information hiding)
Structured Query Language (SQL)
● Standard language used with relational databases to perform queries and manipulate data
Java DataBase Connectivity (JDBC)
● Java programs communicate with databases using JDBC
● JDBC driver implements interface to database
ECE
318
-
Programming
Principles
for
Engineers.
Relational database model
Relational database
● Logical representation of data, not necessarily the way the data is stored
● Table
○ Rows (entities), columns (attributes)
● Primary key (column or group of columns)
○ Unique value for each row
○ Not every table has a primary key
● SQL statement
○ Query (which data to select from table or tables)
ECE
318
-
Programming
Principles
for
Engineers.
Relational database model
What will be the result if we select distinct Department and Location data from
the Employee table?
ECE
318
-
Programming
Principles
for
Engineers.
ECE
318
-
Programming
Principles
for
Engineers.
Example of Relational Database: The Books Database
● Four tables: authors, publishers, authorISBN, and title
● Foreign key is table entry that is a primary key in another table
(enable rows from multiple tables to be joined)
ECE
318
-
Programming
Principles
for
Engineers.
ECE
318
-
Programming
Principles
for
Engineers.
Entity Relationship (ER) diagram
Table relationships in books.
ECE
318
-
Programming
Principles
for
Engineers.
SQL
ECE
318
-
Programming
Principles
for
Engineers.
SQL: SELECT QUERY
Simplest form of a SELECT query
SELECT * FROM tableName
example: SELECT * FROM authors
* means all columns (not recommended)
Select specific fields from a table
SELECT authorID, lastName FROM authors
ECE
318
-
Programming
Principles
for
Engineers.
SQL: SELECT * WHERE
Specify the selection criteria (predicates)
SELECT columnName1, columnName2, … FROM tableName WHERE criteria
SELECT title, editionNumber, copyright
FROM titles
WHERE copyright > 2000
ECE
318
-
Programming
Principles
for
Engineers.
WHERE example
SELECT title, editionNumber, copyright FROM titles WHERE copyright > 2000
ECE
318
-
Programming
Principles
for
Engineers.
WHERE clause
WHERE clause condition operators
<, >, <=, >=, =, <>, LIKE
LIKE (pattern matching)
wildcard characters % and _
% or * (zero or more characters no matter what they are)
_ or ? (single character no matter what it is)
• wildcard string surrounded by single quotes
ECE
318
-
Programming
Principles
for
Engineers.
WHERE clause
SELECT authorID, firstName, lastName
FROM authors
WHERE lastName LIKE ‘D%’
ECE
318
-
Programming
Principles
for
Engineers.
WHERE clause
SELECT authorID, firstName, lastName
FROM authors
WHERE lastName LIKE ‘_i%’
ECE
318
-
Programming
Principles
for
Engineers.
ORDER BY clause
Optional ORDER BY clause
SELECT columnName1, columnName2, … FROM tableNameORDER BY column [ASC]
SELECT columnName1, columnName2, … FROM tableNameORDER BY column DESC
Note that ASC is default (thus optional)
ORDER BY multiple fields
ORDER BY column1 sortingOrder, column2 sortingOrder, …
Combine the WHERE and ORDER BY clauses
–
ECE
318
-
Programming
Principles
for
Engineers.
ORDER BY clause
SELECT authorID, firstName, lastName
FROM authors
ORDER BY lastName ASC
ECE
318
-
Programming
Principles
for
Engineers.
ORDER BY clause
SELECT authorID, firstName, lastName
FROM authors
ORDER BY lastName DESC
ECE
318
-
Programming
Principles
for
Engineers.
ORDER BY clause
SELECT authorID, firstName, lastName
FROM authors
ORDER BY lastName, firstName
ECE
318
-
Programming
Principles
for
Engineers.
ORDER BY clause
SELECT isbn, title, editionNumber, copyright, price
FROM titles WHERE title LIKE ‘%How to Program’
ORDER BY title ASC
ECE
318
-
Programming
Principles
for
Engineers.
Joining: Merging data from multiple tables
Split related data into separate tables to avoid redundancy
Join the tables
Merge data from multiple tables into a single view
INNER JOIN
•SELECT columnName1, columnName2, …
FROM table1
INNER JOIN table2
ON table1.columnName = table2.column2Name
•SELECT firstName, lastName, isbn
FROM authors
INNER JOIN authorISBN
ON authors.authorID = authorISBN.authorID
ORDER BY lastName, firstName
ECE
318
-
Programming
Principles
for
Engineers.
Joining: Merging data from multiple tables
ECE
318
-
Programming
Principles
for
Engineers.
INSERT statement
Insert a row into a table
INSERT INTO tableName ( columnName1, … , columnNameN )
VALUES ( value1, … , valueN )
INSERT INTO authors ( firstName, lastName )
VALUES ( ‘Sue’, ‘Smith’ )
ECE
318
-
Programming
Principles
for
Engineers.
UPDATE statement
UPDATE tableName
SET columnName1 = value1, … , columnNameN = valueN
WHERE criteria
UPDATE authors
SET lastName = ‘Jones’
WHERE lastName = ‘Smith’ AND firstName = ‘Sue’
ECE
318
-
Programming
Principles
for
Engineers.
DELETE statement
Remove data from a table (row or rows)
DELETE FROM tableName WHERE criteria
DELETE FROM authors
WHERE lastName = ‘Jones’ AND firstName = ‘Sue’
ECE
318
-
Programming
Principles
for
Engineers.
Manipulating Databases with JDBC
● Connect to a database
● Query the database
● Display the results of the query
ECE
318
-
Programming
Principles
for
Engineers.
Connection to and Querying a Database
Example: DisplayAuthors.java
Retrieves the entire authors table
Connection object manages connection between Java program and database
connection = DriverManager.getConnection (DATABASE_URL);
URL jdbc:db2j:books specifies communication protocol (jdbc), subprotocol (db2j), name of
database (books)
getConnection overloaded (one version can be used to supply account and password)
ECE
318
-
Programming
Principles
for
Engineers.
Connection to and Querying a Database
Example: DisplayAuthors.java
Retrieves the entire authors table
Displays the data in a JTextArea
Connection object manages connection between Java program and database
connection = DriverManager.getConnection (DATABASE_URL);
URL jdbc:db2j:books specifies communication protocol (jdbc), subprotocol (db2j), name of
database (books)
getConnection overloaded (one version can be used to supply account and password)
1 // Fig. 23.26: DisplayAuthors.java
2 // Displaying the contents of the authors table.
3
4 import java.awt.*;
5 import java.sql.*;
6 import java.util.*;
7 import javax.swing.*;
8
9 public class DisplayAuthors {
10
11 // JDBC driver name and database URL
12 static final String JDBC_DRIVER = "com.ibm.db2j.jdbc.DB2jDriver";
13 static final String DATABASE_URL = "jdbc:db2j:books";
14
15 // declare Connection and Statement for accessing
16 // and querying database
17 private Connection connection;
18 private Statement statement;
19
20 // constructor connects to database, queries database, processes
21 // results and displays results in window
22 public DisplayAuthors()
23 {
24 super( "Authors Table of Books Database" );
25
ECE
318
-
Programming
Principles
for
Engineers.
Connection to and Querying a Database
Example: DisplayAuthors.java
Retrieves the entire authors table
Displays the data in a JTextArea
Connection object manages connection between Java program and database
connection = DriverManager.getConnection (DATABASE_URL);
URL jdbc:db2j:books specifies communication protocol (jdbc), subprotocol (db2j), name of
database (books)
getConnection overloaded (one version can be used to supply account and password)
26 // connect to database books and query database
27 try {
28
29 // specify location of database on filesystem
30 System.setProperty( "db2j.system.home", "C:/Cloudscape_5.0" );
31
32 // load database driver class
33 Class.forName( JDBC_DRIVER );
34
35 // establish connection to database
36 connection = DriverManager.getConnection( DATABASE_URL );
37
38 // create Statement for querying database
39 statement = connection.createStatement();
40
41 // query database
42 ResultSet resultSet =
43 statement.executeQuery( "SELECT * FROM authors" );
44
45 // process query results
46 StringBuffer results = new StringBuffer();
47 ResultSetMetaData metaData = resultSet.getMetaData();
48 int numberOfColumns = metaData.getColumnCount();
49
ECE
318
-
Programming
Principles
for
Engineers.
Connection to and Querying a Database
Example: DisplayAuthors.java
Retrieves the entire authors table
Displays the data in a JTextArea
Connection object manages connection between Java program and database
connection = DriverManager.getConnection (DATABASE_URL);
URL jdbc:db2j:books specifies communication protocol (jdbc), subprotocol (db2j), name of
database (books)
getConnection overloaded (one version can be used to supply account and password)
50 for ( int i = 1; i <= numberOfColumns; i++ )
51 results.append( metaData.getColumnName( i ) + "t" );
52
53 results.append( "n" );
54
55 while ( resultSet.next() ) {
56
57 for ( int i = 1; i <= numberOfColumns; i++ )
58 results.append( resultSet.getObject( i ) + "t" );
59
60 results.append( "n" );
61 }
62
63 72 } // end try
73 75
ECE
318
-
Programming
Principles
for
Engineers.
Connection to and Querying a Database
Example: DisplayAuthors.java
Retrieves the entire authors table
Displays the data in a JTextArea
Connection object manages connection between Java program and database
connection = DriverManager.getConnection (DATABASE_URL);
URL jdbc:db2j:books specifies communication protocol (jdbc), subprotocol (db2j), name of
database (books)
getConnection overloaded (one version can be used to supply account and password)
catch ( SQLException sqlException ) {
76
77
78 // print exception message
79 System.exit( 1 );
80 }
81
82 // detect problems loading database driver
83 catch ( ClassNotFoundException classNotFound ) {
84
85 // print exception message
86
87 System.exit( 1 );
88 }
89
90 // ensure statement and connection are closed properly
91 finally {
92
93 try {
94 statement.close();
95 connection.close();
96 }
97
ECE
318
-
Programming
Principles
for
Engineers.
Connection to and Querying a Database
Example: DisplayAuthors.java
Retrieves the entire authors table
Displays the data in a JTextArea
Connection object manages connection between Java program and database
connection = DriverManager.getConnection (DATABASE_URL);
URL jdbc:db2j:books specifies communication protocol (jdbc), subprotocol (db2j), name of
database (books)
getConnection overloaded (one version can be used to supply account and password)
98 // handle exceptions closing statement and connection
99 catch ( SQLException sqlException ) {
100 JOptionPane.showMessageDialog( null,
101 sqlException.getMessage(), "Database Error",
102 JOptionPane.ERROR_MESSAGE );
103
104 System.exit( 1 );
105 }
106 }
107
108 } // end DisplayAuthors constructor
109
110 // launch the application
111 public static void main( String args[] )
112 {
113 DisplayAuthors window = new DisplayAuthors();
114 window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
115 }
116
117 } // end class DisplayAuthors
ECE
318
-
Programming
Principles
for
Engineers.
Connection to and Querying a Database
Example: DisplayAuthors.java
Retrieves the entire authors table
Displays the data in a JTextArea
Connection object manages connection between Java program and database
connection = DriverManager.getConnection (DATABASE_URL);
URL jdbc:db2j:books specifies communication protocol (jdbc), subprotocol (db2j), name of
database (books)
getConnection overloaded (one version can be used to supply account and password)
98 // handle exceptions closing statement and connection
99 catch ( SQLException sqlException ) {
100 JOptionPane.showMessageDialog( null,
101 sqlException.getMessage(), "Database Error",
102 JOptionPane.ERROR_MESSAGE );
103
104 System.exit( 1 );
105 }
106 }
107
108 } // end DisplayAuthors constructor
109
110 // launch the application
111 public static void main( String args[] )
112 {
113 DisplayAuthors window = new DisplayAuthors();
114 window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
115 }
116
117 } // end class DisplayAuthors

More Related Content

Similar to Java Database Connectivity with JDBC.pptx

Similar to Java Database Connectivity with JDBC.pptx (20)

Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Jsp project module
Jsp project moduleJsp project module
Jsp project module
 
Data access
Data accessData access
Data access
 
JDBC
JDBCJDBC
JDBC
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
Jdbc
JdbcJdbc
Jdbc
 
SQL Optimizer vs Hive
SQL Optimizer vs Hive SQL Optimizer vs Hive
SQL Optimizer vs Hive
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
Query optimization and processing for advanced database systems
Query optimization and processing for advanced database systemsQuery optimization and processing for advanced database systems
Query optimization and processing for advanced database systems
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Enterprise Spring
Enterprise SpringEnterprise Spring
Enterprise Spring
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3
 
Jdbc
JdbcJdbc
Jdbc
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLink
 
Final Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.pptFinal Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.ppt
 

Recently uploaded

ALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdfALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdfMadan Karki
 
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWINGBRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWINGKOUSTAV SARKAR
 
Theory for How to calculation capacitor bank
Theory for How to calculation capacitor bankTheory for How to calculation capacitor bank
Theory for How to calculation capacitor banktawat puangthong
 
ChatGPT Prompt Engineering for project managers.pdf
ChatGPT Prompt Engineering for project managers.pdfChatGPT Prompt Engineering for project managers.pdf
ChatGPT Prompt Engineering for project managers.pdfqasastareekh
 
15-Minute City: A Completely New Horizon
15-Minute City: A Completely New Horizon15-Minute City: A Completely New Horizon
15-Minute City: A Completely New HorizonMorshed Ahmed Rahath
 
Online book store management system project.pdf
Online book store management system project.pdfOnline book store management system project.pdf
Online book store management system project.pdfKamal Acharya
 
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisSeismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisDr.Costas Sachpazis
 
Interfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdfInterfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdfragupathi90
 
Supermarket billing system project report..pdf
Supermarket billing system project report..pdfSupermarket billing system project report..pdf
Supermarket billing system project report..pdfKamal Acharya
 
Electrical shop management system project report.pdf
Electrical shop management system project report.pdfElectrical shop management system project report.pdf
Electrical shop management system project report.pdfKamal Acharya
 
Teachers record management system project report..pdf
Teachers record management system project report..pdfTeachers record management system project report..pdf
Teachers record management system project report..pdfKamal Acharya
 
E-Commerce Shopping using MERN Stack where different modules are present
E-Commerce Shopping using MERN Stack where different modules are presentE-Commerce Shopping using MERN Stack where different modules are present
E-Commerce Shopping using MERN Stack where different modules are presentjatinraor66
 
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdfInvolute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdfJNTUA
 
Linux Systems Programming: Semaphores, Shared Memory, and Message Queues
Linux Systems Programming: Semaphores, Shared Memory, and Message QueuesLinux Systems Programming: Semaphores, Shared Memory, and Message Queues
Linux Systems Programming: Semaphores, Shared Memory, and Message QueuesRashidFaridChishti
 
2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edge2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edgePaco Orozco
 
DR PROF ING GURUDUTT SAHNI WIKIPEDIA.pdf
DR PROF ING GURUDUTT SAHNI WIKIPEDIA.pdfDR PROF ING GURUDUTT SAHNI WIKIPEDIA.pdf
DR PROF ING GURUDUTT SAHNI WIKIPEDIA.pdfDrGurudutt
 
Circuit Breaker arc phenomenon.pdf engineering
Circuit Breaker arc phenomenon.pdf engineeringCircuit Breaker arc phenomenon.pdf engineering
Circuit Breaker arc phenomenon.pdf engineeringKanchhaTamang
 
Intelligent Agents, A discovery on How A Rational Agent Acts
Intelligent Agents, A discovery on How A Rational Agent ActsIntelligent Agents, A discovery on How A Rational Agent Acts
Intelligent Agents, A discovery on How A Rational Agent ActsSheetal Jain
 
Fabrication Of Automatic Star Delta Starter Using Relay And GSM Module By Utk...
Fabrication Of Automatic Star Delta Starter Using Relay And GSM Module By Utk...Fabrication Of Automatic Star Delta Starter Using Relay And GSM Module By Utk...
Fabrication Of Automatic Star Delta Starter Using Relay And GSM Module By Utk...ShivamTiwari995432
 
Introduction to Heat Exchangers: Principle, Types and Applications
Introduction to Heat Exchangers: Principle, Types and ApplicationsIntroduction to Heat Exchangers: Principle, Types and Applications
Introduction to Heat Exchangers: Principle, Types and ApplicationsKineticEngineeringCo
 

Recently uploaded (20)

ALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdfALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
 
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWINGBRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
 
Theory for How to calculation capacitor bank
Theory for How to calculation capacitor bankTheory for How to calculation capacitor bank
Theory for How to calculation capacitor bank
 
ChatGPT Prompt Engineering for project managers.pdf
ChatGPT Prompt Engineering for project managers.pdfChatGPT Prompt Engineering for project managers.pdf
ChatGPT Prompt Engineering for project managers.pdf
 
15-Minute City: A Completely New Horizon
15-Minute City: A Completely New Horizon15-Minute City: A Completely New Horizon
15-Minute City: A Completely New Horizon
 
Online book store management system project.pdf
Online book store management system project.pdfOnline book store management system project.pdf
Online book store management system project.pdf
 
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisSeismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
 
Interfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdfInterfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdf
 
Supermarket billing system project report..pdf
Supermarket billing system project report..pdfSupermarket billing system project report..pdf
Supermarket billing system project report..pdf
 
Electrical shop management system project report.pdf
Electrical shop management system project report.pdfElectrical shop management system project report.pdf
Electrical shop management system project report.pdf
 
Teachers record management system project report..pdf
Teachers record management system project report..pdfTeachers record management system project report..pdf
Teachers record management system project report..pdf
 
E-Commerce Shopping using MERN Stack where different modules are present
E-Commerce Shopping using MERN Stack where different modules are presentE-Commerce Shopping using MERN Stack where different modules are present
E-Commerce Shopping using MERN Stack where different modules are present
 
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdfInvolute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
 
Linux Systems Programming: Semaphores, Shared Memory, and Message Queues
Linux Systems Programming: Semaphores, Shared Memory, and Message QueuesLinux Systems Programming: Semaphores, Shared Memory, and Message Queues
Linux Systems Programming: Semaphores, Shared Memory, and Message Queues
 
2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edge2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edge
 
DR PROF ING GURUDUTT SAHNI WIKIPEDIA.pdf
DR PROF ING GURUDUTT SAHNI WIKIPEDIA.pdfDR PROF ING GURUDUTT SAHNI WIKIPEDIA.pdf
DR PROF ING GURUDUTT SAHNI WIKIPEDIA.pdf
 
Circuit Breaker arc phenomenon.pdf engineering
Circuit Breaker arc phenomenon.pdf engineeringCircuit Breaker arc phenomenon.pdf engineering
Circuit Breaker arc phenomenon.pdf engineering
 
Intelligent Agents, A discovery on How A Rational Agent Acts
Intelligent Agents, A discovery on How A Rational Agent ActsIntelligent Agents, A discovery on How A Rational Agent Acts
Intelligent Agents, A discovery on How A Rational Agent Acts
 
Fabrication Of Automatic Star Delta Starter Using Relay And GSM Module By Utk...
Fabrication Of Automatic Star Delta Starter Using Relay And GSM Module By Utk...Fabrication Of Automatic Star Delta Starter Using Relay And GSM Module By Utk...
Fabrication Of Automatic Star Delta Starter Using Relay And GSM Module By Utk...
 
Introduction to Heat Exchangers: Principle, Types and Applications
Introduction to Heat Exchangers: Principle, Types and ApplicationsIntroduction to Heat Exchangers: Principle, Types and Applications
Introduction to Heat Exchangers: Principle, Types and Applications
 

Java Database Connectivity with JDBC.pptx

  • 1. L10. Java Database Connectivity with JDBC
  • 3. ECE 318 - Programming Principles for Engineers. Introduction DataBase Management System (DBMS) ● Mechanisms for storing and organizing data ● Access, store, modify data without concern for internal representation (information hiding) Structured Query Language (SQL) ● Standard language used with relational databases to perform queries and manipulate data Java DataBase Connectivity (JDBC) ● Java programs communicate with databases using JDBC ● JDBC driver implements interface to database
  • 4. ECE 318 - Programming Principles for Engineers. Relational database model Relational database ● Logical representation of data, not necessarily the way the data is stored ● Table ○ Rows (entities), columns (attributes) ● Primary key (column or group of columns) ○ Unique value for each row ○ Not every table has a primary key ● SQL statement ○ Query (which data to select from table or tables)
  • 5. ECE 318 - Programming Principles for Engineers. Relational database model What will be the result if we select distinct Department and Location data from the Employee table?
  • 7. ECE 318 - Programming Principles for Engineers. Example of Relational Database: The Books Database ● Four tables: authors, publishers, authorISBN, and title ● Foreign key is table entry that is a primary key in another table (enable rows from multiple tables to be joined)
  • 11. ECE 318 - Programming Principles for Engineers. SQL: SELECT QUERY Simplest form of a SELECT query SELECT * FROM tableName example: SELECT * FROM authors * means all columns (not recommended) Select specific fields from a table SELECT authorID, lastName FROM authors
  • 12. ECE 318 - Programming Principles for Engineers. SQL: SELECT * WHERE Specify the selection criteria (predicates) SELECT columnName1, columnName2, … FROM tableName WHERE criteria SELECT title, editionNumber, copyright FROM titles WHERE copyright > 2000
  • 13. ECE 318 - Programming Principles for Engineers. WHERE example SELECT title, editionNumber, copyright FROM titles WHERE copyright > 2000
  • 14. ECE 318 - Programming Principles for Engineers. WHERE clause WHERE clause condition operators <, >, <=, >=, =, <>, LIKE LIKE (pattern matching) wildcard characters % and _ % or * (zero or more characters no matter what they are) _ or ? (single character no matter what it is) • wildcard string surrounded by single quotes
  • 15. ECE 318 - Programming Principles for Engineers. WHERE clause SELECT authorID, firstName, lastName FROM authors WHERE lastName LIKE ‘D%’
  • 16. ECE 318 - Programming Principles for Engineers. WHERE clause SELECT authorID, firstName, lastName FROM authors WHERE lastName LIKE ‘_i%’
  • 17. ECE 318 - Programming Principles for Engineers. ORDER BY clause Optional ORDER BY clause SELECT columnName1, columnName2, … FROM tableNameORDER BY column [ASC] SELECT columnName1, columnName2, … FROM tableNameORDER BY column DESC Note that ASC is default (thus optional) ORDER BY multiple fields ORDER BY column1 sortingOrder, column2 sortingOrder, … Combine the WHERE and ORDER BY clauses –
  • 18. ECE 318 - Programming Principles for Engineers. ORDER BY clause SELECT authorID, firstName, lastName FROM authors ORDER BY lastName ASC
  • 19. ECE 318 - Programming Principles for Engineers. ORDER BY clause SELECT authorID, firstName, lastName FROM authors ORDER BY lastName DESC
  • 20. ECE 318 - Programming Principles for Engineers. ORDER BY clause SELECT authorID, firstName, lastName FROM authors ORDER BY lastName, firstName
  • 21. ECE 318 - Programming Principles for Engineers. ORDER BY clause SELECT isbn, title, editionNumber, copyright, price FROM titles WHERE title LIKE ‘%How to Program’ ORDER BY title ASC
  • 22. ECE 318 - Programming Principles for Engineers. Joining: Merging data from multiple tables Split related data into separate tables to avoid redundancy Join the tables Merge data from multiple tables into a single view INNER JOIN •SELECT columnName1, columnName2, … FROM table1 INNER JOIN table2 ON table1.columnName = table2.column2Name •SELECT firstName, lastName, isbn FROM authors INNER JOIN authorISBN ON authors.authorID = authorISBN.authorID ORDER BY lastName, firstName
  • 24. ECE 318 - Programming Principles for Engineers. INSERT statement Insert a row into a table INSERT INTO tableName ( columnName1, … , columnNameN ) VALUES ( value1, … , valueN ) INSERT INTO authors ( firstName, lastName ) VALUES ( ‘Sue’, ‘Smith’ )
  • 25. ECE 318 - Programming Principles for Engineers. UPDATE statement UPDATE tableName SET columnName1 = value1, … , columnNameN = valueN WHERE criteria UPDATE authors SET lastName = ‘Jones’ WHERE lastName = ‘Smith’ AND firstName = ‘Sue’
  • 26. ECE 318 - Programming Principles for Engineers. DELETE statement Remove data from a table (row or rows) DELETE FROM tableName WHERE criteria DELETE FROM authors WHERE lastName = ‘Jones’ AND firstName = ‘Sue’
  • 27. ECE 318 - Programming Principles for Engineers. Manipulating Databases with JDBC ● Connect to a database ● Query the database ● Display the results of the query
  • 28. ECE 318 - Programming Principles for Engineers. Connection to and Querying a Database Example: DisplayAuthors.java Retrieves the entire authors table Connection object manages connection between Java program and database connection = DriverManager.getConnection (DATABASE_URL); URL jdbc:db2j:books specifies communication protocol (jdbc), subprotocol (db2j), name of database (books) getConnection overloaded (one version can be used to supply account and password)
  • 29. ECE 318 - Programming Principles for Engineers. Connection to and Querying a Database Example: DisplayAuthors.java Retrieves the entire authors table Displays the data in a JTextArea Connection object manages connection between Java program and database connection = DriverManager.getConnection (DATABASE_URL); URL jdbc:db2j:books specifies communication protocol (jdbc), subprotocol (db2j), name of database (books) getConnection overloaded (one version can be used to supply account and password) 1 // Fig. 23.26: DisplayAuthors.java 2 // Displaying the contents of the authors table. 3 4 import java.awt.*; 5 import java.sql.*; 6 import java.util.*; 7 import javax.swing.*; 8 9 public class DisplayAuthors { 10 11 // JDBC driver name and database URL 12 static final String JDBC_DRIVER = "com.ibm.db2j.jdbc.DB2jDriver"; 13 static final String DATABASE_URL = "jdbc:db2j:books"; 14 15 // declare Connection and Statement for accessing 16 // and querying database 17 private Connection connection; 18 private Statement statement; 19 20 // constructor connects to database, queries database, processes 21 // results and displays results in window 22 public DisplayAuthors() 23 { 24 super( "Authors Table of Books Database" ); 25
  • 30. ECE 318 - Programming Principles for Engineers. Connection to and Querying a Database Example: DisplayAuthors.java Retrieves the entire authors table Displays the data in a JTextArea Connection object manages connection between Java program and database connection = DriverManager.getConnection (DATABASE_URL); URL jdbc:db2j:books specifies communication protocol (jdbc), subprotocol (db2j), name of database (books) getConnection overloaded (one version can be used to supply account and password) 26 // connect to database books and query database 27 try { 28 29 // specify location of database on filesystem 30 System.setProperty( "db2j.system.home", "C:/Cloudscape_5.0" ); 31 32 // load database driver class 33 Class.forName( JDBC_DRIVER ); 34 35 // establish connection to database 36 connection = DriverManager.getConnection( DATABASE_URL ); 37 38 // create Statement for querying database 39 statement = connection.createStatement(); 40 41 // query database 42 ResultSet resultSet = 43 statement.executeQuery( "SELECT * FROM authors" ); 44 45 // process query results 46 StringBuffer results = new StringBuffer(); 47 ResultSetMetaData metaData = resultSet.getMetaData(); 48 int numberOfColumns = metaData.getColumnCount(); 49
  • 31. ECE 318 - Programming Principles for Engineers. Connection to and Querying a Database Example: DisplayAuthors.java Retrieves the entire authors table Displays the data in a JTextArea Connection object manages connection between Java program and database connection = DriverManager.getConnection (DATABASE_URL); URL jdbc:db2j:books specifies communication protocol (jdbc), subprotocol (db2j), name of database (books) getConnection overloaded (one version can be used to supply account and password) 50 for ( int i = 1; i <= numberOfColumns; i++ ) 51 results.append( metaData.getColumnName( i ) + "t" ); 52 53 results.append( "n" ); 54 55 while ( resultSet.next() ) { 56 57 for ( int i = 1; i <= numberOfColumns; i++ ) 58 results.append( resultSet.getObject( i ) + "t" ); 59 60 results.append( "n" ); 61 } 62 63 72 } // end try 73 75
  • 32. ECE 318 - Programming Principles for Engineers. Connection to and Querying a Database Example: DisplayAuthors.java Retrieves the entire authors table Displays the data in a JTextArea Connection object manages connection between Java program and database connection = DriverManager.getConnection (DATABASE_URL); URL jdbc:db2j:books specifies communication protocol (jdbc), subprotocol (db2j), name of database (books) getConnection overloaded (one version can be used to supply account and password) catch ( SQLException sqlException ) { 76 77 78 // print exception message 79 System.exit( 1 ); 80 } 81 82 // detect problems loading database driver 83 catch ( ClassNotFoundException classNotFound ) { 84 85 // print exception message 86 87 System.exit( 1 ); 88 } 89 90 // ensure statement and connection are closed properly 91 finally { 92 93 try { 94 statement.close(); 95 connection.close(); 96 } 97
  • 33. ECE 318 - Programming Principles for Engineers. Connection to and Querying a Database Example: DisplayAuthors.java Retrieves the entire authors table Displays the data in a JTextArea Connection object manages connection between Java program and database connection = DriverManager.getConnection (DATABASE_URL); URL jdbc:db2j:books specifies communication protocol (jdbc), subprotocol (db2j), name of database (books) getConnection overloaded (one version can be used to supply account and password) 98 // handle exceptions closing statement and connection 99 catch ( SQLException sqlException ) { 100 JOptionPane.showMessageDialog( null, 101 sqlException.getMessage(), "Database Error", 102 JOptionPane.ERROR_MESSAGE ); 103 104 System.exit( 1 ); 105 } 106 } 107 108 } // end DisplayAuthors constructor 109 110 // launch the application 111 public static void main( String args[] ) 112 { 113 DisplayAuthors window = new DisplayAuthors(); 114 window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 115 } 116 117 } // end class DisplayAuthors
  • 34. ECE 318 - Programming Principles for Engineers. Connection to and Querying a Database Example: DisplayAuthors.java Retrieves the entire authors table Displays the data in a JTextArea Connection object manages connection between Java program and database connection = DriverManager.getConnection (DATABASE_URL); URL jdbc:db2j:books specifies communication protocol (jdbc), subprotocol (db2j), name of database (books) getConnection overloaded (one version can be used to supply account and password) 98 // handle exceptions closing statement and connection 99 catch ( SQLException sqlException ) { 100 JOptionPane.showMessageDialog( null, 101 sqlException.getMessage(), "Database Error", 102 JOptionPane.ERROR_MESSAGE ); 103 104 System.exit( 1 ); 105 } 106 } 107 108 } // end DisplayAuthors constructor 109 110 // launch the application 111 public static void main( String args[] ) 112 { 113 DisplayAuthors window = new DisplayAuthors(); 114 window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 115 } 116 117 } // end class DisplayAuthors