Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Changing Data Using SQL

Problem

You wish to insert or update data, create a new table, delete a table, or otherwise change the database.

Solution

Instead of executeQuery( ), use executeUpdate( ) and SQL commands to make the change.

Discussion

The executeUpdate( ) method is used when you want to make a change to the database, as opposed to getting a list of rows with a query. You can implement either data changes like insert or update, data structure changes like create table, or almost anything that you can do by sending SQL directly to the database through its own update command interface or GUI.

The program listed in Example 20-10 converts the User database from the text file format of Section 20.2 into a relational database. Note that I destroy the table before creating it, just in case there was an older version in place. If there was not, executeUpdate( ) simply indicates this in its return code; it doesn’t throw an exception. Then the program creates the table and its index. Finally, it goes into a loop reading the lines from the text file; for each, a prepared statement is used to insert the user’s information into the database.

Example 20-10. TextToJDBC.java

package jabadot; import java.sql.*; import java.io.*; import java.util.*; /** Convert the database from text form to JDBC form. */ public class TextToJDBC { protected final static String TEXT_NAME = "userdb.txt"; protected final static String DB_URL = "jdbc:idb:userdb.prp"; public static void main(String[] fn) throws ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata