Home arrow Java arrow Page 5 - Reading and Writing Data Using JDBC and XML

Reading and Writing Data Using JDBC and XML

For those who want to delve deeply into Java, this article explores Java Database Connectivity (JDBC), a class library that connects Java programs to relational databases. The first of three parts, it is excerpted from chapter 20 of the book Sams Teach Yourself Java 2 in 21 Days, 4th Edition, written by Rogers Cadenhead and Laura Lemay (Sams; ISBN: 0672326280).

Author Info:
By: Sams Publishing
Rating: 4 stars4 stars4 stars4 stars4 stars / 9
June 08, 2006
  1. · Reading and Writing Data Using JDBC and XML
  2. · Database Drivers
  3. · Connecting to an ODBC Data Source
  4. · Retrieving Data from a Database Using SQL
  5. · Writing Data to a Database Using SQL

print this article

Reading and Writing Data Using JDBC and XML - Writing Data to a Database Using SQL
(Page 5 of 5 )

In the CoalTotals application, you retrieved data from a database using an SQL statement prepared as a string, like this:

SELECT * FROM Coal WHERE (Country='Swaziland')

This is a common way to use SQL. You could write a program that asks a user to enter an SQL query and then displays the result (though this isn't a good idea—SQL queries can be used to delete records, tables, and even entire databases).

The java.sql package also supports another way to create an SQL statement: a prepared statement.

A prepared statement, which is represented by the PreparedStatement class, is an SQL statement that is compiled before it is executed. This enables the statement to return data more quickly and is a better choice if you are executing an SQL statement repeatedly in the same program.

Tip - Prepared statements also have another advantage on Windows systems: They make it possible to write data to a Microsoft Access database using the JDBC-ODBC driver. For several years, I've had no luck at all writing data from Java to Access using statements, but I can use prepared statements without any trouble. I can't figure out why. I'm hoping another author writes a book titled Teach Yourself Why Microsoft Access Hates My Unprepared SQL Statements in 21 Days.

To create a prepared statement, call a connection's prepareStatement(String) method with a string that indicates the structure of the SQL statement.

To indicate the structure, you write an SQL statement in which parameters have been replaced with question marks.

Here's an example for a connection object called cc:

PreparedStatement ps = cc.prepareStatement(
"SELECT * FROM Coal WHERE (Country='?') ORDER BY

Here's another example with more than one question mark:

PreparedStatement ps = cc.prepareStatement(

The question marks in these SQL statements are placeholders for data. Before you can execute the statement, you must put data in each of these places using one of the methods of the PreparedStatement class.

To put data into a prepared statement, you must call a method with the position of the placeholder followed by the data to insert.

For example, to put the string "Swaziland" in the first prepared statement, call the setString(int, String) method:

ps.setString(1, "Swaziland");

The first argument indicates the position of the placeholder, numbered from left to right. The first question mark is 1, the second is 2, and so on.

The second argument is the data to put in the statement at that position.

The following methods are available:

  • setAsciiStream(int, InputStream, int)—At the position indicated by the first argument, inserts the specified InputStream, which represents a stream of ASCII characters. The third argument indicates how many bytes from the input stream to insert.

  • setBinaryStream(int, InputStream, int)—At the position indicated by the first argument, inserts the specified InputStream, which represents a stream of bytes. The third argument indicates the number of bytes to insert from the stream.

  • setCharacterStream(int, Reader, int)—At the position indicated by the first argument, inserts the specified Reader, which represents a character stream. The third argument indicates the number of characters to insert from the stream.

  • setBoolean(int, boolean)—Inserts a boolean value at the position indicated by the integer.

  • setByte(int, byte)—Inserts a byte value at the indicated position.

  • setBytes(int, byte[])—Inserts an array of bytes at the indicated position.

  • setDate(int, Date)—Inserts a Date object (from the java.sql package) at the indicated position.

  • setDouble(int, double)—Inserts a double value at the indicated position.

  • setFloat(int, float)—Inserts a float value at the indicated position.

  • setInt(int, int)—Inserts an int value at the indicated position.

  • setLong(int, long)—Inserts a long value at the indicated position.

  • setShort(int, short)—Inserts a short value at the indicated position.

  • setString(int, String)—Inserts a String value at the indicated position.

There's also a setNull(int, int) method that stores SQL's version of a null (empty) value at the position indicated by the first argument.

The second argument to setNull() should be a class variable from the Types class in java.sql to indicate what kind of SQL value belongs in that position.

There are class variables for each of the SQL data types. This list, which is not complete, includes some of the most commonly used variables: BIGINT, BIT, CHAR, DATE, DECIMAL, DOUBLE, FLOAT, INTEGER, SMALLINT, TINYINT, and VARCHAR.

The following code puts a null CHAR value at the fifth position in a prepared statement called ps:

ps.setNull(5, Types.CHAR);

The next project demonstrates the use of a prepared statement to add stock quote data to a database. Quotes are collected from the Yahoo! Web site.

As a service to people who follow the stock market, Yahoo! offers a Download Spreadsheet link on its main stock quote page for each ticker symbol.

To see this link, look up a stock quote on Yahoo! or go directly to a page such as this one:


Below the price chart, you can find a Download Data link. Here's what the link looks like for Sun Microsystems:


You can click this link to open the file or save it to a folder on your system. The file, which is only one line long, contains the stock's price and volume data saved at the last market close. Here's an example of what Sun's data looked like on March 8, 2004:


The fields in this data, in order, are the ticker symbol, closing price, date, time, price change since yesterday's close, daily low, daily high, daily open, and volume.

The QuoteData application uses each of these fields except one—the time, which isn't particularly useful because it's always the time the market closed.

The following takes place in the program:

  • The ticker symbol of a stock is taken as a command-line argument.

  • A QuoteData object is created with the ticker symbol as an instance variable called ticker.

  • The object's retrieveQuote() method is called to download the stock data from Yahoo! and return it as a String.

  • The object's storeQuote() method is called with that String as an argument. It saves the stock data to a database using a JDBC-ODBC connection.

The last task requires a stock quote database, which can be reached through JDBC-ODBC, set up to collect this data.

Windows users can download quotedata.mdb, a Microsoft Access 2000 database created to hold Yahoo!'s stock quote data, from the book's Web site. Visit http://www.java21days.com and open the Day 20 page. After you download the database (or create one of your own), use the ODBC Data Source administrator to create a new data source associated with the database. This application assumes that the name of the source is QuoteData.

Enter the text of Listing 20.2 into your editor and save the file as QuoteData.java.

Listing 20.2 The Full Text of QuoteData.java
 1: import java.io.*;
2: import java.net.*;
3: import java.sql.*;
4: import java.util.*;
6: public class QuoteData {
7:   private String ticker;
9:   public QuoteData(String inTicker) {
10:     ticker = inTicker;
11:   }
13:   private String retrieveQuote() {
14:     StringBuffer buf = new StringBuffer();
15:     try {
16:       URL page = new URL("http://
quote.yahoo.com/d/quotes.csv?s=" + 17: ticker + "&f=sl1d1t1c1ohgv&e=.csv"); 18: String line; 19: URLConnection conn = page.openConnection()
; 20: conn.connect(); 21: InputStreamReader in= new
InputStreamReader( 22: conn.getInputStream()); 23: BufferedReader data =
new BufferedReader(in); 24: while ((line = data.readLine()) != null)
{ 25: buf.append(line + "\n"); 26: } 27: } catch (MalformedURLException mue) { 28: System.out.println("Bad URL: " +
mue.getMessage()); 29: } catch (IOException ioe) { 30: System.out.println("IO Error:" +
ioe.getMessage()); 31: } 32: return buf.toString(); 33: } 34: 35: private void storeQuote(String data) { 36: StringTokenizer tokens =
new StringTokenizer(data, ","); 37: String[] fields = new String[9]; 38: for (int i = 0; i < fields.length; i++) { 39: fields[i] =
stripQuotes(tokens.nextToken()); 40: } 41: String datasource = "jdbc:odbc:QuoteData"; 42: try { 43: Class.forName("sun.jdbc.odbc.
JdbcOdbcDriver"); 44: Connection conn =
DriverManager.getConnection( 45: datasource, "", ""); 46: PreparedStatement prep2 =
conn.prepareStatement( 47: "INSERT INTO " + 48: "Stocks(ticker, price, quoteDate,
change, open, " + 49: "high, low, volume) " + 50: "VALUES(?, ?, ?, ?, ?, ?, ?, ?)"); 51: prep2.setString(1, fields[0]); 52: prep2.setString(2, fields[1]); 53: prep2.setString(3, fields[2]); 54: prep2.setString(4, fields[4]); 55: prep2.setString(5, fields[5]); 56: prep2.setString(6, fields[6]); 57: prep2.setString(7, fields[7]); 58: prep2.setString(8, fields[8]); 59: prep2.executeUpdate(); 60: conn.close(); 61: } catch (SQLException sqe) { 62: System.out.println("SQL Error: " +
sqe.getMessage()); 63: } catch (ClassNotFoundException cnfe) { 64: System.out.println(cnfe.getMessage()); 65: } 66: } 67: 68: private String stripQuotes(String input) { 69: StringBuffer output = new StringBuffer(); 70: for (int i = 0; i < input.length(); i++) { 71: if (input.charAt(i) != '\"') { 72: output.append(input.charAt(i)); 73: } 74: } 75: return output.toString(); 76: } 77: 78: public static void main(String[] arguments) { 79: if (arguments.length < 1) { 80: System.out.println("Usage:
java QuoteData tickerSymbol"); 81: System.exit(0); 82: } 83: QuoteData qd = new QuoteData(arguments[0]); 84: String data = qd.retrieveQuote(); 85: qd.storeQuote(data); 86: } 87: }

After you compile the QuoteData application, connect to the Internet and run the program. Remember to specify a valid ticker symbol as a command-line argument. To load the current quote for SUNW (Sun Microsystems):

java QuoteData SUNW

The retrieveQuote() method (lines 13–33) downloads the quote data from Yahoo! and saves it as a string. The techniques used in this method were covered on Day 17, "Communicating Across the Internet."

The storeQuote() method (lines 35–66) uses the SQL techniques covered in this section.

The method begins by splitting up the quote data into a set of string tokens, using the , character as the delimiter between each token. The tokens are then stored in a String array with nine elements.

The array contains the same fields as the Yahoo! data in the same order: ticker symbol, closing price, date, time, price change, low, high, open, and volume.

Next, a data connection to the QuoteData data source is created using the JDBC-ODBC driver (lines 41–45).

This connection is then used to create a prepared statement (lines 46–50). This statement uses the INSERT INTO SQL statement, which causes data to be stored in a database. In this case, the database is quotedata.mdb, and the INSERT INTO statement refers to the Stocks table in that database.

Eight placeholders are in the prepared statement. Only eight are needed, instead of nine, because the application does not use the time field from the Yahoo! data.

A series of setString() methods puts the elements of the String array into the prepared statement, in the same order that the fields exist in the database: ticker symbol, closing price, date, price change, low, high, open, and volume (lines 51–58).

Some fields in the Yahoo! data are dates, floating-point numbers, and integers, so you might think that it would be better to use setDate(), setFloat(), and setInt() for that data.

However, Microsoft Access 2000 does not support some of these methods when you are using SQL to work with the database, even though they exist in Java. If you try to use an unsupported method, such as setFloat(), an SQLException error occurs.

It's easier to send Access strings and let the database program convert them automatically into the right format. This is likely to be true when you are working with other databases; the level of SQL support varies based on the product and ODBC driver involved.

After the prepared statement has been prepared and all the placeholders are filled, the statement's executeUpdate() method is called (line 59). This either adds the quote data to the database or throws an SQL error. The private method stripQuotes() is used to remove quotation marks from Yahoo!'s stock data. This method is called on line 39 to take care of three fields that contain extraneous quotes: the ticker symbol, date, and time.

Please check back next week for the continuation of this article.

DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials