JDBC  «Prev  Next »

Lesson 10Writing information to a database
Objective Write code that adds information to a database.

Write information to Database using JDBC

Writing information to a database is simpler than reading it, because you do it in a single step.
You build an UPDATE or INSERT statement of SQL, and execute it. You don’t use executeQuery(), but rather executeUpdate(), because the drivers need to know that this SQL will actually change the database.
Here is an example of an UPDATE statement:

UPDATE PEOPLE 
SET NUMBER=100 WHERE NAME = 'Kate'

This will find every record in the PEOPLE table with “Kate” in the NAME field, and set the NUMBER field for all of them to 100.
To find every record in the table with a NAME field that matches the name variable and set the NUMBER field to the value of the number variable, you might write code something like this:
// code omitted that sets name and number
Statement stmt = con.createStatement();
stmt.executeUpdate("UPDATE PEOPLE SET NUMBER="
                    + number
                    + " WHERE NAME = '"
                    + name
                    + "'");
stmt.close();

WHERE clause

Be very careful to include a WHERE clause in every UPDATE statement. With no WHERE clause, the fields will be updated in every record in the database. If the WHERE clause is omitted, then every record in the database will be updated.
If your WHERE clause does not match any records in the database, an SQL error message will be shown to the users of your web page. Prevent this by only issuing UPDATE statements when you are sure there is at least one matching record in the database.
The next lesson reviews some terms and concepts introduced in this module.

Write Information to Database - Exercise

Write your own database-enabled servlet.
Write Information to Database - Exercise