An Introduction to JDBC
this example, but can also be an internet hostname or IP address. The
port number for the mysql server is 3306 and the name of the database
is test. Other parameters can be passed in the database URL such as
userid and password.
A connection object is obtained via a call to the getConnection method
of the driver manager. It lets you use the JDBC driver to manage
queries. The userid and password are in clear text in the file. The
password is encrypted by the JDBC driver before passing the
information to the mysql server. A statement object is required to
issue a query. The statement object is obtained by calling the
createStatement method of the connection object.
The SQL query is stored in a string and passed to the executeQuery
method of the statement object which returns a ResultSet object. The
resultSet object contains the results of the query. The next method of
the resultSet object moves the current row forward by one. It returns
false after the last row. This method must be called to advance to the
first row and can be called in a loop to retrieve data from all
matching rows. The resultSet object contains a number of methods to
extract data from a row. For example, to retrieve a string, the
getString method is used. Similarly, to retrieve an integer, the
getInt method is used. Other methods to retrieve a byte, short, long,
float, double boolean, date, time, and a blob are included. The
getBytes method can be used to retrieve a binary large object (blob).
The parameter to these methods is either an integer or a string. The
integer is the column number of the row retrieved. All columns of a
table need not be retrieved. The string is the name of the column
label.
Once data has been extracted from the resultSet object, it is closed.
Another SQL query can be issued and the resultSet object can be
re-used. The statement object can also re-used. The statement and
connection objects are closed when database retrieval is complete.
This simple example illustrates the process of retrieving data from a
database table. It is also possible to update tables and obtain
information about tables. When updating tables, the executeUpdate
method of the statement object is used. For example -
String query = "update test_table set phone = 999-9999 ";
query += "where name = "John Smith"";
- « first
- ‹ previous
- of 7
- next ›
- last »