Java data access

Page 104

Chapter 6: Working with Result Sets ResultSet.getXXX(int columnIndex) ResultSet.getXXX(String columnName)

The first method enables you to retrieve the result set data based on the ordinal column position. The column numbers start at 1, not 0 as Java array indices do. The second method uses the column name to retrieve the data, as shown in the following code snippet: //Assume a valid Connection, conn. Statement stmt = conn.createStatement(); //Create a ResultSet object String SQL = "SELECT Name FROM Employees"; ResultSet rset = stmt.executeQuery(SQL); //Retrieve by ordinal column position String byColumnNumber = rset.getString(1); //Retrieve by column name String byColumnName = rset.getString("name");

Tip You can refer to columns in a result set by their names, which may be easier for you than having to remember the column number. The ResultSet object also has getXXX() methods with which to access the following SQL3 data types: CLOB, BLOB, ARRAY, STRUCT, REF, and DISTINCT. This method gives you access to the data using an SQL LOCATOR, which is a logical pointer on the client that refers to data on the server. As a result you do not materialize the data on the client using the getXXX() methods. You must explicitly perform this task to retrieve the data on the client. You may use an input stream to materialize columns that contain large amounts of binary or character data such as BLOB and CLOB. The methods getBinaryStream() and getAsciiStream() return InputStream objects, so you can control the data download to prevent extremely large values from consuming too much memory. XRef

Refer to Chapter 7, “Understanding JDBC Data Types,” for a more complete explanation of using the SQL3 data types and the ResultSet. getObject() method.

Here is an example of using an InputStream to retrieve column information: //Assume a valid Statement object Sting SQL = "SELECT Data FROM DataTable"; ResultSet rset = stmt.executeQuery (SQL); //Loop through the result set while (rset.next()){ //Use an input stream to store the data InputStream is = rset.getBinaryStream (1); //Collect results from InputStream into a //ByteArrayOutputStream object int i; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while((i = is.read ()) != −1){ bos.write(i); } }

92


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.