SlideShare a Scribd company logo
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
1
Chapter 41 Advanced Java Database
Programming
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
2
Objectives
To create a universal SQL client for accessing local or
remote database (§41.2).
To execute SQL statements in a batch mode (§41.3).
To process updateable and scrollable result sets (§41.4).
To simplify Java database programming using RowSet
(§41.5).
To create a custom table model for RowSet (§41.5).
To store and retrieve images in JDBC (§41.7).
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
3
Example:
Creating an Interactive SQL Client
Connect to any
JDBC data source.
SQLClient Run
Entering and executing SQL
commands interactively
The execution result is displayed for the
SELECT queries, and the execution status is
displayed for the non-SELECT commands.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
4
Batch Updates
To improve performance, JDBC 2 introduced the batch update for
processing nonselect SQL commands. A batch update consists of a
sequence of nonselect SQL commands. These commands are
collected in a batch and submitted to the database all together.
Statement statement = conn.createStatement();
// Add SQL commands to the batch
statement.addBatch("create table T (C1 integer, C2 varchar(15))");
statement.addBatch("insert into T values (100, 'Smith')");
statement.addBatch("insert into T values (200, 'Jones')");
// Execute the batch
int count[] = statement.executeBatch();
The executeBatch() method returns an array
of counts, each of which counts the number
of the rows affected by the SQL command.
The first count returns 0 because it is a DDL
command. The rest of the commands return
1 because only one row is affected.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
5
Example: Copying Text Files to Table
Write a program that gets data from a text file and copies the data to
a table. The text file consists of the lines, each of which corresponds
to a row in the table. The fields in a row are separated by commas.
The string values in a row are enclosed in single quotes. You can
view the text file by clicking the View File button and copy the text
to the table by clicking the Copy button. The table must already be
defined in the database.
CopyFileToTable Run
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
6
Scrollable and Updateable Result Set
The result sets used in the preceding examples are read sequentially.
A result set maintains a cursor pointing to its current row of data.
Initially the cursor is positioned before the first row. The next()
method moves the cursor forward to the next row. This is known as
sequential forward reading. It is the only way of processing the rows
in a result set that is supported by JDBC 1.
With JDBC 2, you can scroll the rows both forward and backward
and move the cursor to a desired location using the first, last, next,
previous, absolute, or relative method. Additionally, you can insert,
delete, or update a row in the result set and have the changes
automatically reflected in the database.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
7
Creating Scrollable Statements
To obtain a scrollable or updateable result set, you must first create a
statement with an appropriate type and concurrency mode. For a
static statement, use
Statement statement = connection.createStatement
(int resultSetType, int resultSetConcurrency);
For a prepared statement, use
PreparedStatement statement = connection.prepareStatement
(String sql, int resultSetType, int resultSetConcurrency);
The resulting set is scrollable
ResultSet resultSet = statement.executeQuery(query);
TYPE_FORWARD_ONLY
TYPE_SCROLL_INSENSITIVE
TYPE_SCROLL_SENSITIVE
CONCUR_READ_ONLY
CONCUR_UPDATABLE
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
8
Example: Scrolling and Updating Table
Develop a useful utility that displays all the rows of a database table in a JTable
and uses a scrollable and updateable result set to navigate the table and modify its
contents. defined in the database.
TestTableEditor Run
Insert a new row
TableEditor NewRecordDialog
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
9
RowSet: JdbcRowSet and CachedRowSet
JDBC 2 introduced a new RowSet interface that can be used to simplify database
programming. The RowSet interface extends java.sql.ResultSet with additional
capabilities that allow a RowSet instance to be configured to connect to a JDBC
url, username, password, set a SQL command, execute the command, and
retrieve the execution result.
«interface»
java.sql.ResultSet
«interface»
javax.sql.RowSet
«interface»
javax.sql.rowset.JdbcRowSet
«interface»
javax.sql.rowset.CachedRowSet
com.sun.rowset.JdbcRowSetImpl com.sun.rowset.CachedRowSetImpl
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
10
SQL BLOB and CLOB Types
Database can store not only numbers and strings, but also images. SQL3
introduced a new data type BLOB (Binary Large OBject) for storing binary
data, which can be used to store images.
Another new SQL3 type is CLOB (Character Large OBject) for storing a large
text in the character format. JDBC 2 introduced the interfaces java.sql.Blob
and java.sql.Clob to support mapping for these new SQL types. JBDC 2 also
added new methods, such as getBlob, setBinaryStream, getClob, setBlob, and
setClob, in the interfaces ResultSet and PreparedStatement to access SQL
BLOB, and CLOB values.
To store an image into a cell in a table, the corresponding column for the cell
must be of the BLOB type. For example, the following SQL statement creates
a table whose type for the flag column is BLOB.
create table Country(name varchar(30), flag blob,
description varchar(255));
BLOB
CLOB
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
11
Storing and Retrieving Images in JDBC
To insert a record with images to a table, define a prepared statement like this
one:
PreparedStatement pstmt = connection.prepareStatement(
"insert into Country values(?, ?, ?)");
Images are usually stored in files. You may first get an instance of InputStream
for an image file and then use the setBinaryStream method to associate the
input stream with a cell in the table, as follows:
// Store image to the table cell
File file = new File(imageFilenames[i]);
InputStream inputImage = new FileInputStream(file);
pstmt.setBinaryStream(2, inputImage, (int)(file.length()));
To retrieve an image from a table, use the getBlob method, as shown below:
// Store image to the table cell
Blob blob = rs.getBlob(1);
ImageIcon imageIcon = new ImageIcon(
blob.getBytes(1, (int)blob.length()));
Store
image
Retrieve
image
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
12
Example: Scrolling and Updating Table
In this example, you will create a table, populate it with data, including images, and
retrieve and display images. The table is named Country. Each record in the table
consists of three fields: name, flag, and description. Flag is an image field. The
program first creates the table and stores data to it. Then the program retrieves the
country names from the table and adds them to a combo box. When the user selects
a name from the combo box, the country’s flag and description are displayed.
StoreAndRetrieveImage Run

More Related Content

PPT
4. Database Connectivity using JDBC .ppt
HITENKHEMANI
 
PDF
java4th.pdf bilgisayar mühendisliği bölümü
Smeyyeztrk10
 
PPTX
Advance Java Programming (CM5I)5.Interacting with-database
Payal Dungarwal
 
PPT
jdbc_presentation.ppt
DrMeenakshiS
 
PPS
Jdbc api
kamal kotecha
 
DOC
Java database connectivity notes for undergraduate
RameshPrasadBhatta2
 
PPT
Java jdbc
Arati Gadgil
 
4. Database Connectivity using JDBC .ppt
HITENKHEMANI
 
java4th.pdf bilgisayar mühendisliği bölümü
Smeyyeztrk10
 
Advance Java Programming (CM5I)5.Interacting with-database
Payal Dungarwal
 
jdbc_presentation.ppt
DrMeenakshiS
 
Jdbc api
kamal kotecha
 
Java database connectivity notes for undergraduate
RameshPrasadBhatta2
 
Java jdbc
Arati Gadgil
 

Similar to 41slideAdvancedDatabaseProgramming.ppt (20)

PPTX
Database Access With JDBC
Dharani Kumar Madduri
 
PPTX
Unit No 5 Files and Database Connectivity.pptx
DrYogeshDeshmukh1
 
PPTX
Database connect
Yoga Raja
 
PPTX
3.java database connectivity
web360
 
PPT
Select query in JDBC
Maulik Togadiya
 
PPSX
JDBC Part - 2
Hitesh-Java
 
PPT
Scrollable Updatable
phanleson
 
PPT
Scrollable Updatable
leminhvuong
 
PPT
JDBC – Java Database Connectivity
Information Technology
 
PPTX
Session 24 - JDBC, Intro to Enterprise Java
PawanMM
 
PPT
Executing Sql Commands
leminhvuong
 
PPT
Executing Sql Commands
phanleson
 
PPTX
Java database connectivity
Atul Saurabh
 
DOCX
Java beans
Sher Singh Bardhan
 
PDF
Jdbc
mishaRani1
 
PPTX
Mule jdbc
Rajarajan Sadhasivam
 
PDF
Presentation for java data base connectivity
kanjariya006
 
PPTX
Java Databse Connectvity- Alex Jose
Dipayan Sarkar
 
PPTX
Database Connectivity with JDBC
Dudy Ali
 
Database Access With JDBC
Dharani Kumar Madduri
 
Unit No 5 Files and Database Connectivity.pptx
DrYogeshDeshmukh1
 
Database connect
Yoga Raja
 
3.java database connectivity
web360
 
Select query in JDBC
Maulik Togadiya
 
JDBC Part - 2
Hitesh-Java
 
Scrollable Updatable
phanleson
 
Scrollable Updatable
leminhvuong
 
JDBC – Java Database Connectivity
Information Technology
 
Session 24 - JDBC, Intro to Enterprise Java
PawanMM
 
Executing Sql Commands
leminhvuong
 
Executing Sql Commands
phanleson
 
Java database connectivity
Atul Saurabh
 
Java beans
Sher Singh Bardhan
 
Presentation for java data base connectivity
kanjariya006
 
Java Databse Connectvity- Alex Jose
Dipayan Sarkar
 
Database Connectivity with JDBC
Dudy Ali
 

More from MohammedNouh7 (14)

DOCX
Chapterunifiedmo 3 UML Class Diagram.docx
MohammedNouh7
 
PPT
Chapterunifiedmodelinglanguagetwouml2.ppt
MohammedNouh7
 
PPT
Chapteroneofunifiedmodelinglanguage1.ppt
MohammedNouh7
 
PPT
JavaProgramming 17321_CS202-Chapter8.ppt
MohammedNouh7
 
PPTX
Chapter7 database management system.pptx
MohammedNouh7
 
PPTX
Introduction to database m Chapter 9.pptx
MohammedNouh7
 
PPT
database management system lessonchapter
MohammedNouh7
 
PPT
Chapter 1.ppt
MohammedNouh7
 
PPTX
Lecture2.pptx
MohammedNouh7
 
PPTX
Ch13.pptx
MohammedNouh7
 
PPTX
Ch21.pptx
MohammedNouh7
 
PPT
34slideDatabaseProgramming.ppt
MohammedNouh7
 
PPT
11slide.ppt
MohammedNouh7
 
PPT
10slide.ppt
MohammedNouh7
 
Chapterunifiedmo 3 UML Class Diagram.docx
MohammedNouh7
 
Chapterunifiedmodelinglanguagetwouml2.ppt
MohammedNouh7
 
Chapteroneofunifiedmodelinglanguage1.ppt
MohammedNouh7
 
JavaProgramming 17321_CS202-Chapter8.ppt
MohammedNouh7
 
Chapter7 database management system.pptx
MohammedNouh7
 
Introduction to database m Chapter 9.pptx
MohammedNouh7
 
database management system lessonchapter
MohammedNouh7
 
Chapter 1.ppt
MohammedNouh7
 
Lecture2.pptx
MohammedNouh7
 
Ch13.pptx
MohammedNouh7
 
Ch21.pptx
MohammedNouh7
 
34slideDatabaseProgramming.ppt
MohammedNouh7
 
11slide.ppt
MohammedNouh7
 
10slide.ppt
MohammedNouh7
 

Recently uploaded (20)

PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PPTX
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PPT
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Software Development Company | KodekX
KodekX
 
Doc9.....................................
SofiaCollazos
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Software Development Methodologies in 2025
KodekX
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 

41slideAdvancedDatabaseProgramming.ppt

  • 1. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 41 Advanced Java Database Programming
  • 2. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 2 Objectives To create a universal SQL client for accessing local or remote database (§41.2). To execute SQL statements in a batch mode (§41.3). To process updateable and scrollable result sets (§41.4). To simplify Java database programming using RowSet (§41.5). To create a custom table model for RowSet (§41.5). To store and retrieve images in JDBC (§41.7).
  • 3. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 3 Example: Creating an Interactive SQL Client Connect to any JDBC data source. SQLClient Run Entering and executing SQL commands interactively The execution result is displayed for the SELECT queries, and the execution status is displayed for the non-SELECT commands.
  • 4. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 4 Batch Updates To improve performance, JDBC 2 introduced the batch update for processing nonselect SQL commands. A batch update consists of a sequence of nonselect SQL commands. These commands are collected in a batch and submitted to the database all together. Statement statement = conn.createStatement(); // Add SQL commands to the batch statement.addBatch("create table T (C1 integer, C2 varchar(15))"); statement.addBatch("insert into T values (100, 'Smith')"); statement.addBatch("insert into T values (200, 'Jones')"); // Execute the batch int count[] = statement.executeBatch(); The executeBatch() method returns an array of counts, each of which counts the number of the rows affected by the SQL command. The first count returns 0 because it is a DDL command. The rest of the commands return 1 because only one row is affected.
  • 5. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 5 Example: Copying Text Files to Table Write a program that gets data from a text file and copies the data to a table. The text file consists of the lines, each of which corresponds to a row in the table. The fields in a row are separated by commas. The string values in a row are enclosed in single quotes. You can view the text file by clicking the View File button and copy the text to the table by clicking the Copy button. The table must already be defined in the database. CopyFileToTable Run
  • 6. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 6 Scrollable and Updateable Result Set The result sets used in the preceding examples are read sequentially. A result set maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next() method moves the cursor forward to the next row. This is known as sequential forward reading. It is the only way of processing the rows in a result set that is supported by JDBC 1. With JDBC 2, you can scroll the rows both forward and backward and move the cursor to a desired location using the first, last, next, previous, absolute, or relative method. Additionally, you can insert, delete, or update a row in the result set and have the changes automatically reflected in the database.
  • 7. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 7 Creating Scrollable Statements To obtain a scrollable or updateable result set, you must first create a statement with an appropriate type and concurrency mode. For a static statement, use Statement statement = connection.createStatement (int resultSetType, int resultSetConcurrency); For a prepared statement, use PreparedStatement statement = connection.prepareStatement (String sql, int resultSetType, int resultSetConcurrency); The resulting set is scrollable ResultSet resultSet = statement.executeQuery(query); TYPE_FORWARD_ONLY TYPE_SCROLL_INSENSITIVE TYPE_SCROLL_SENSITIVE CONCUR_READ_ONLY CONCUR_UPDATABLE
  • 8. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 8 Example: Scrolling and Updating Table Develop a useful utility that displays all the rows of a database table in a JTable and uses a scrollable and updateable result set to navigate the table and modify its contents. defined in the database. TestTableEditor Run Insert a new row TableEditor NewRecordDialog
  • 9. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 9 RowSet: JdbcRowSet and CachedRowSet JDBC 2 introduced a new RowSet interface that can be used to simplify database programming. The RowSet interface extends java.sql.ResultSet with additional capabilities that allow a RowSet instance to be configured to connect to a JDBC url, username, password, set a SQL command, execute the command, and retrieve the execution result. «interface» java.sql.ResultSet «interface» javax.sql.RowSet «interface» javax.sql.rowset.JdbcRowSet «interface» javax.sql.rowset.CachedRowSet com.sun.rowset.JdbcRowSetImpl com.sun.rowset.CachedRowSetImpl
  • 10. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 10 SQL BLOB and CLOB Types Database can store not only numbers and strings, but also images. SQL3 introduced a new data type BLOB (Binary Large OBject) for storing binary data, which can be used to store images. Another new SQL3 type is CLOB (Character Large OBject) for storing a large text in the character format. JDBC 2 introduced the interfaces java.sql.Blob and java.sql.Clob to support mapping for these new SQL types. JBDC 2 also added new methods, such as getBlob, setBinaryStream, getClob, setBlob, and setClob, in the interfaces ResultSet and PreparedStatement to access SQL BLOB, and CLOB values. To store an image into a cell in a table, the corresponding column for the cell must be of the BLOB type. For example, the following SQL statement creates a table whose type for the flag column is BLOB. create table Country(name varchar(30), flag blob, description varchar(255)); BLOB CLOB
  • 11. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 11 Storing and Retrieving Images in JDBC To insert a record with images to a table, define a prepared statement like this one: PreparedStatement pstmt = connection.prepareStatement( "insert into Country values(?, ?, ?)"); Images are usually stored in files. You may first get an instance of InputStream for an image file and then use the setBinaryStream method to associate the input stream with a cell in the table, as follows: // Store image to the table cell File file = new File(imageFilenames[i]); InputStream inputImage = new FileInputStream(file); pstmt.setBinaryStream(2, inputImage, (int)(file.length())); To retrieve an image from a table, use the getBlob method, as shown below: // Store image to the table cell Blob blob = rs.getBlob(1); ImageIcon imageIcon = new ImageIcon( blob.getBytes(1, (int)blob.length())); Store image Retrieve image
  • 12. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 12 Example: Scrolling and Updating Table In this example, you will create a table, populate it with data, including images, and retrieve and display images. The table is named Country. Each record in the table consists of three fields: name, flag, and description. Flag is an image field. The program first creates the table and stores data to it. Then the program retrieves the country names from the table and adds them to a combo box. When the user selects a name from the combo box, the country’s flag and description are displayed. StoreAndRetrieveImage Run