SlideShare a Scribd company logo
1 of 12
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

Similar to 41slideAdvancedDatabaseProgramming.ppt

3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivityweb360
 
Scrollable Updatable
Scrollable UpdatableScrollable Updatable
Scrollable Updatableleminhvuong
 
Scrollable Updatable
Scrollable UpdatableScrollable Updatable
Scrollable Updatablephanleson
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaPawanMM
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsphanleson
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityAtul Saurabh
 
Java Databse Connectvity- Alex Jose
Java Databse Connectvity- Alex JoseJava Databse Connectvity- Alex Jose
Java Databse Connectvity- Alex JoseDipayan Sarkar
 
Database Connectivity with JDBC
Database Connectivity with JDBCDatabase Connectivity with JDBC
Database Connectivity with JDBCDudy Ali
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsFulvio Corno
 
Java session17
Java session17Java session17
Java session17Niit Care
 

Similar to 41slideAdvancedDatabaseProgramming.ppt (20)

3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivity
 
Select query in JDBC
Select query in JDBCSelect query in JDBC
Select query in JDBC
 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
 
Scrollable Updatable
Scrollable UpdatableScrollable Updatable
Scrollable Updatable
 
Scrollable Updatable
Scrollable UpdatableScrollable Updatable
Scrollable Updatable
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise Java
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Java beans
Java beansJava beans
Java beans
 
Jdbc
JdbcJdbc
Jdbc
 
Mule jdbc
Mule   jdbcMule   jdbc
Mule jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Java Databse Connectvity- Alex Jose
Java Databse Connectvity- Alex JoseJava Databse Connectvity- Alex Jose
Java Databse Connectvity- Alex Jose
 
Database Connectivity with JDBC
Database Connectivity with JDBCDatabase Connectivity with JDBC
Database Connectivity with JDBC
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
Java session17
Java session17Java session17
Java session17
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 

More from MohammedNouh7

JavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.pptJavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.pptMohammedNouh7
 
Chapter7 database management system.pptx
Chapter7 database management system.pptxChapter7 database management system.pptx
Chapter7 database management system.pptxMohammedNouh7
 
Introduction to database m Chapter 9.pptx
Introduction to database m Chapter 9.pptxIntroduction to database m Chapter 9.pptx
Introduction to database m Chapter 9.pptxMohammedNouh7
 
database management system lessonchapter
database management system lessonchapterdatabase management system lessonchapter
database management system lessonchapterMohammedNouh7
 
34slideDatabaseProgramming.ppt
34slideDatabaseProgramming.ppt34slideDatabaseProgramming.ppt
34slideDatabaseProgramming.pptMohammedNouh7
 

More from MohammedNouh7 (11)

JavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.pptJavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.ppt
 
Chapter7 database management system.pptx
Chapter7 database management system.pptxChapter7 database management system.pptx
Chapter7 database management system.pptx
 
Introduction to database m Chapter 9.pptx
Introduction to database m Chapter 9.pptxIntroduction to database m Chapter 9.pptx
Introduction to database m Chapter 9.pptx
 
database management system lessonchapter
database management system lessonchapterdatabase management system lessonchapter
database management system lessonchapter
 
Chapter 1.ppt
Chapter 1.pptChapter 1.ppt
Chapter 1.ppt
 
Lecture2.pptx
Lecture2.pptxLecture2.pptx
Lecture2.pptx
 
Ch13.pptx
Ch13.pptxCh13.pptx
Ch13.pptx
 
Ch21.pptx
Ch21.pptxCh21.pptx
Ch21.pptx
 
34slideDatabaseProgramming.ppt
34slideDatabaseProgramming.ppt34slideDatabaseProgramming.ppt
34slideDatabaseProgramming.ppt
 
11slide.ppt
11slide.ppt11slide.ppt
11slide.ppt
 
10slide.ppt
10slide.ppt10slide.ppt
10slide.ppt
 

Recently uploaded

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 

Recently uploaded (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 

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