A Basic Java Object For Storing Results Although the JDBC provides you with the ResultSet class to get the data from an SQL query, you will still need to store and format within your program the results for display. The smart way to do this is in a re-usable fashion (by implementing a generic object or class) which allows you to re-use the same class you develop to retrieve data from a query in any of your JDBC programs. The code snippet in Listing 7.1 is a method that will keep your results in a Java object until you are ready to parse and display it. Let s begin by defining the data we will be getting from the source, and determining how we want to structure it within our Java applet. Remember that the ResultSet allows us to retrieve data in a row-by-row, column-by-column fashion; it simply gives us sequential access to the resulting table data. Table 7.1 shows the example table we will be using in this chapter. Table 7.1 Example table. emp_no first_name last_name salary 01234 Pratik Patel 8000 1235 Karl Moss 23000 0002 Keith Weiskamp 90000 0045 Ron Pronk 59999 53000 The optimal way to store this data in our Java program is to put each column s data in its own structure and then link the different columns by using an index; this will allow us to keep the columnar relationship of the table intact. We will put each column s data in an array. To simplify matters, we ll use the getString method, which translates the different data types returned by a query into a String type. Then, we ll take the data in a column and delimit the instances with commas. We ll use an array of String to do this; each place in the array will represent a different column. The data object we will create is shown here: table_data[0] => 01234,1235,0002,0045,0067 table_data[1] => Pratik,Karl,Keith,Ron,David table_data[2] => Patel,Moss,Weiskamp,Pronk,Friedel table_data[3] => 8000,23000,90000,59999,53000 Listing 7.1 shows the method we ll use to query the database and return a String array that contains the resulting table data. Listing 7.1 The getData method. public String[] getData( String QueryLine ) { // Run the QueryLine SQL query, and return the resulting columns in an // array of String. The first column is at index [0], the second at [1], // etc.
Please check java servlet web hosting services, here you will find professional-grade java servlet web hosting with the best prices.