O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required