Java Reference
In-Depth Information
System.out.println(resultSet.getString(
1
) +
" "
+
resultSet.getString(
2
) +
" "
+ resultSet.getString(
3
));
The
getString(1)
,
getString(2)
, and
getString(3)
methods retrieve the col-
umn values for
firstName
,
mi
, and
lastName
, respectively. Alternatively, you can use
getString("firstName")
,
getString("mi")
, and
getString("lastName")
to
retrieve the same three column values. The first execution of the
next()
method sets the cur-
rent row to the first row in the result set, and subsequent invocations of the
next()
method
set the current row to the second row, third row, and so on, to the last row.
Listing 32.1 is a complete example that demonstrates connecting to a database, executing
a simple query, and processing the query result with JDBC. The program connects to a local
MySQL database and displays the students whose last name is
Smith
.
L
ISTING
32.1
SimpleJDBC.java
1
import
java.sql.*;
2
3
public class
SimpleJdbc {
4
public static void
main(String[] args)
5
throws
SQLException, ClassNotFoundException {
6
// Load the JDBC driver
7 Class.forName(
"com.mysql.jdbc.Driver"
);
8 System.out.println(
"Driver loaded"
);
9
10
// Connect to a database
11 Connection connection = DriverManager.getConnection
12 (
"jdbc:mysql://localhost/javabook"
,
"scott"
,
"tiger"
);
13 System.out.println(
"Database connected"
);
14
15
load driver
connect database
// Create a statement
16
Statement statement = connection.createStatement();
create statement
17
18
// Execute a statement
19
ResultSet resultSet = statement.executeQuery
execute statement
20
(
"select firstName, mi, lastName from Student where lastName "
21
+
" = 'Smith'"
);
22
23
// Iterate through the result and print the student names
24
while
(resultSet.next())
25 System.out.println(resultSet.getString(
1
) +
"\t"
+
26
get result
resultSet.getString(
2
) +
"\t"
+ resultSet.getString(
3
));
27
28
// Close the connection
29
connection.close();
close connection
30 }
31 }
The statement in line 7 loads a JDBC driver for MySQL, and the statement in lines 11-13
connects to a local MySQL database. You can change them to connect to an Access or Oracle
database. The program creates a
Statement
object (line 16), executes an SQL statement and
returns a
ResultSet
object (lines 19-21), and retrieves the query result from the
ResultSet
object (lines 24-26). The last statement (line 29) closes the connection and releases resources
related to the connection. You can rewrite this program using the try-with-resources syntax.
Note
If you run this program from the DOS prompt, specify the appropriate driver in the
classpath, as shown in FigureĀ 32.22.
run from DOS prompt
Search WWH ::
Custom Search