Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
18.1 Basic Steps in Using JDBC
465
Create a Statement
A
Statement
object is used to send queries and commands to the database
and is created from the
Connection
as follows:
Statement statement = connection.createStatement();
Execute a Query
Once you have a
Statement
object, you can use it to send SQL queries by
using the
executeQuery
method, which returns an object of type
Result
Set
. Here is an example:
String query = "SELECT col1, col2, col3 FROM sometable";
ResultSet resultSet = statement.executeQuery(query);
To modify the database, use
executeUpdate
instead of
executeQuery
,
and supply a string that uses
UPDATE
,
INSERT
, or
DELETE
. Other useful meth
ods in the
Statement
class include
execute
(execute an arbitrary command)
and
setQueryTimeout
(set a maximum delay to wait for results). You can
also create parameterized queries where values are supplied to a precom
piled fixed format query. See Section 18.6 for details.
Process the Results
The simplest way to handle the results is to process them one row at a time,
using the
ResultSet
's
next
method to move through the table a row at a
time. Within a row,
ResultSet
provides various
get
Xxx methods that take a
column index or column name as an argument and return the result as a vari
ety of different Java types. For instance, use
getInt
if the value should be an
integer,
getString
for a
String
, and so on for most other data types. If you
just want to display the results, you can use
getString
regardless of the
actual column type. However, if you use the version that takes a column
index, note that columns are indexed starting at 1 (following the SQL conven
tion), not at 0 as with arrays, vectors, and most other data structures in the
Java programming language.
Core Warning
The first column in a
ResultSet
row has index 1, not 0.
Here is an example that prints the values of the first three columns in all
rows of a
ResultSet
.
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved