Java Reference
In-Depth Information
RDBMS
Database URL format
Microsoft SQL Server
jdbc:sqlserver:// hostname : portNumber ;databaseName= dataBaseName
Sybase
jdbc:sybase:Tds: hostname : portNumber / databaseName
Fig. 24.24 | Popular JDBC database URL formats. (Part 2 of 2.)
Software Engineering Observation 24.3
Most database management systems require the user to log in before accessing the database
contents. DriverManager method getConnection is overloaded with versions that enable
the program to supply the username and password to gain access.
Creating a Statement for Executing Queries
Line 22 of Fig. 24.23 invokes Connection method createStatement to obtain an object
that implements interface Statement (package java.sql ). The program uses the State-
ment object to submit SQL statements to the database.
Executing a Query
Line 23 use the Statement object's executeQuery method to submit a query that selects
all the author information from table Authors . This method returns an object that imple-
ments interface ResultSet and contains the query results. The ResultSet methods enable
the program to manipulate the query result.
Processing a Query's ResultSet
Lines 26-42 process the ResultSet . Line 26 obtains the ResultSet 's ResultSetMetaData
(package java.sql ) object. The metadata describes the ResultSet 's contents. Programs
can use metadata programmatically to obtain information about the ResultSet 's column
names and types. Line 27 uses ResultSetMetaData method getColumnCount to retrieve
the number of columns in the ResultSet . Lines 32-33 display the column names.
Software Engineering Observation 24.4
Metadata enables programs to process ResultSet contents dynamically when detailed
information about the ResultSet is not known in advance.
Lines 37-42 display the data in each ResultSet row. First, the program positions the
ResultSet cursor (which points to the row being processed) to the first row in the
ResultSet with method next (line 37). Method next returns boolean value true if it's
able to position to the next row; otherwise, the method returns false .
Common Programming Error 24.5
Initially, a ResultSet cursor is positioned before the first row. A SQLException occurs if
you attempt to access a ResultSet 's contents before positioning the ResultSet cursor to
the first row with method next .
If there are rows in the ResultSet , lines 39-40 extract and display the contents of
each column in the current row. When a ResultSet is processed, each column can be
extracted as a specific Java type— ResultSetMetaData method getColumnType returns a
 
Search WWH ::




Custom Search