Java Reference
In-Depth Information
Display 19.12
Creating a Derby Embedded Database and Table
(part 2 of 2)
36 s.execute("INSERT INTO names " +
37 "VALUES ('Simmons, Dan', 2, 'http://www.dansimmons.com')");
38 s.execute("INSERT INTO names " +
39 "VALUES ('Stephenson, Neal', 3, " +
"'http://www.nealstephenson.com')");
40 System.out.println("Authors inserted.");
41 conn.close();
42 }
43
catch
(SQLException err)
44 {
45 System.err.println("SQL error.");
46 err.printStackTrace(System.err);
47 System.exit(0);
48 }
49 }
50 }
Sample Dialogue
Loaded the embedded driver.
Connecting to and creating the database.
Database created.
Created 'names' table.
Inserting authors.
Authors inserted.
Display 19.13 shows how to retrieve rows from an existing database and table
using the
SELECT
statement. The syntax of the
SELECT
statement is given in the box
“Common SQL Statements.” The desired fields must be specified or an * placed after
the
SELECT
statement to retrieve all fields. After specifying the name of the table, an
optional
WHERE
clause may be inserted that contains conditions that must be met,
much like the Boolean condition you might place after an if statement. If the
WHERE
clause is left off, then all rows from the table will be retrieved. Otherwise, only those
rows that match the conditions of the
WHERE
clause are returned.
A
SELECT
statement can be executed by invoking the
executeQuery( )
method of
a
Statement
object. The return value is an object of type
ResultSet
. The
ResultSet
object maintains a cursor to each matching row in the database. Initially, the cursor
is positioned before the first row. The
next( )
method is used to advance the
cursor to the next row. If there is no next row, then
false
is returned. Otherwise,
true
is returned. Typically, a
while
loop is used to iterate over all rows in the set
by looping until the
next( )
method returns
false
. Note that iteration is forward