3 messages in com.mysql.lists.javaRE: Need help - Exception detected in...
FromSent OnAttachments
Barry Kimelman26 Jan 2004 13:15 
Kevin Fries26 Jan 2004 13:21 
Mark Matthews26 Jan 2004 13:27 
Subject:RE: Need help - Exception detected in getString() method
From:Kevin Fries (kfr@kurant.com)
Date:01/26/2004 01:21:25 PM
List:com.mysql.lists.java

To properly find out how many columns are in your result set, use: ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount();

-----Original Message----- From: Barry Kimelman [mailto:whea@mts.net] Sent: Monday, January 26, 2004 1:16 PM To: ja@lists.mysql.com Subject: Need help - Exception detected in getString() method

I am having a problem using rs.getString(int) to retrieve all the columns in a MySQL database table record.

My system is Linux Redhat9. My JDBC is "MySQL Connector/J 3.1.0".

This is my first test program for MySQL JDBC processing. This program is a port of the same program I used under a DB2 database on Windows NT4 a few years ago (the program worked fine on Windows). This test program is just meant to display the contents of an arbitrary table (ie. the user specifies the table to be dumped by an argument to the java program).

I can connect to the database with no problem. my problem is trying to retrieve all the columns in a database table record using the getString() method with an integer argument (ie. the argument is the column number).

Here is the part of my code which is having the problem :

// retrieve data from the database System.out.println("Retrieve some data from the database..."); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * from customer");

System.out.println("Received results:");

// display the result set // rs.next() returns false when there are no more rows while (rs.next()) { for ( count = 1 ; rs.getString(count) != null ; ++count ) { System.out.print(rs.getString(count) + " "); } // FOR loop over retrieved columns System.out.print("\n"); } // WHILE displaying SELECT results

rs.close(); stmt.close();

The database table in question has 3 columns (all of type varchar).

The problem is that the "for" loop goes too far !! It prints the 3 columns of the table record and then it attempts to display the 4th column which causes an exception since there are only 3 columns in the table record structure! The exception is :

java.sql.SQLException: Column Index out of range ( 4 >3)

I thought the basic functionality of getString() would be the same for all JDBC implementations! Anyway for "MySQL Connector/J" how does the getstring(int) method indicate that you have "run off the end of the record"? Or is there a better way to determine the number of columns in a database table record structure under MySQL (or even all databases in general) ?