Sams Teach Yourself Java 6 in 21 Days 5th phần 8 pdf

73 396 1
Sams Teach Yourself Java 6 in 21 Days 5th phần 8 pdf

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

The data source WorldEnergy is associated with a Microsoft Access driver, according to Figure 18.2. Most Windows database programs include one or more ODBC dri- vers that correspond to the format. Microsoft Access includes ODBC drivers that can be used to connect to an Access database file. Connecting to an ODBC Data Source Your first project today is a Java application that uses a JDBC-ODBC bridge to connect to an Access file. The Access file for this project is world20.mdb, a database of world energy statistics published by the U.S. Energy Information Administration. The Coal table in this data- base includes three fields you will be using in the project: n Country n Year n Anthracite Production The database used in this project is included on this book’s official website at http:// www.java21days.com. To use this database, you must have an ODBC driver on your system that supports Access files. Using the ODBC Data Source Administrator (or a similar program if you’re on a non-Windows system), you must create a new ODBC data source associated with world20.mdb. The JDBC-ODBC Bridge 489 18 FIGURE 18.2 A listing of data sources in the ODBC Data Sources Administrator. NOTE Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Other setup work might be needed depending on the ODBC drivers present on your sys- tem, if any. Consult the documentation included with the ODBC driver. After you have downloaded world20.mdb to your computer or found another database that’s compatible with the ODBC drivers on your system, the final step in getting the file ready for JDBC-ODBC is to create a data source associated with it. Unlike other input- output classes in Java, JDBC doesn’t use a filename to identify a data file and use its contents. Instead, a tool such as the ODBC Data Source Administrator is used to name the ODBC source and indicate the file folder where it can be found. In the ODBC Data Source Administrator, click the User DSN tab to see a list of data sources that are available. To add a new one associated with world20.mdb (or your own database), click the Add button, choose an ODBC driver, and then click the Finish button. A Setup window opens that you can use to provide a name, short description, and other information about the database. Click the Select button to find and choose the database file. Figure 18.3 shows the Setup window used to set up world20.mdb as a data source in the ODBC Data Source Administrator. 490 DAY 18: Accessing Databases with JDBC FIGURE 18.3 The ODBC driver Setup window. After a database has been associated with an ODBC data source, working with it in a Java program is relatively easy if you are conversant with SQL. The first task in a JDBC program is to load the driver (or drivers) that will be used to connect to a data source. A driver is loaded with the Class.forName(String) method. Class, part of the java.lang package, can be used to load classes into the Java inter- preter. The forName(String) method loads the class named by the specified string. A ClassNotFoundException can be thrown by this method. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com All programs that use an ODBC data source use sun.jdbc.odbc.JdbcOdbcDriver, the JDBC-ODBC bridge driver included with Java. Loading this class into a Java interpreter requires the following statement: Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); After the driver has been loaded, you can establish a connection to the data source by using the DriverManager class in the java.sql package. The getConnection(String, String, String) method of DriverManager can be used to set up the connection. It returns a reference to a Connection object representing an active data connection. The three arguments of this method are as follows: n A name identifying the data source and the type of database connectivity used to reach it n A username n A password The last two items are needed only if the data source is secured with a username and a password. If not, these arguments can be null strings (“”). The name of the data source is preceded by the text jdbc:odbc: when using the JDBC- ODBC bridge, which indicates the type of database connectivity in use. The following statement could be used to connect to a data source called Payroll with a username of “Doc” and a password of “1rover1”: Connection payday = DriverManager.getConnection( “jdbc:odbc:Payroll”, “Doc”, “1rover1”); After you have a connection, you can reuse it each time you want to retrieve or store information from that connection’s data source. The getConnection() method and all others called on a data source throw SQLException errors if something goes wrong as the data source is being used. SQL has its own error messages, and they are passed along as part of SQLException objects. Retrieving Data from a Database Using SQL An SQL statement is represented in Java by a Statement object. Statement is an inter- face, so it can’t be instantiated directly. However, an object that implements the interface The JDBC-ODBC Bridge 491 18 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com is returned by the createStatement() method of a Connection object, as in the follow- ing example: Statement lookSee = payday.CreateStatement(); After you have a Statement object, you can use it to conduct an SQL query by calling the object’s executeQuery(String) method. The String argument should be an SQL query that follows the syntax of that language. It’s beyond the scope of today’s lesson to teach SQL, a rich, data- retrieval and storage language that has its own book in this series: Sams Teach Yourself SQL in 21 Days, 4th Edition by Ron Plew and Ryan Stephens (ISBN: 0-672-32451-2). Although you need to learn SQL to do any extensive work with it, much of the language is easy to pick up from any examples you can find, such as those you will work with today. The following is an example of an SQL query that could be used on the Coal table of the world20.mdb database: SELECT Country, Year, ‘Anthracite Production’ FROM Coal WHERE (Country Is Not Null) ORDER BY Year This SQL query retrieves several fields for each record in the database for which the Country field is not equal to null. The records returned are sorted according to their Country field, so Afghanistan would precede Burkina Faso. The following Java statement executes that query on a Statement object named looksee: ResultSet set = looksee.executeQuery( “SELECT Country, Year, ‘Anthracite Production’ FROM Coal “ + “WHERE (Country Is Not Null) ORDER BY Year”); If the SQL query has been phrased correctly, the executeQuery() method returns a ResultSet object holding all the records that have been retrieved from the data source. To add records to a database instead of retrieving them, the state- ment’s executeUpdate() method should be called. You will work with this later. 492 DAY 18: Accessing Databases with JDBC CAUTION NOTE Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com When a ResultSet is returned from executeQuery(), it is positioned at the first record that has been retrieved. The following methods of ResultSet can be used to pull infor- mation from the current record: n getDate(String)—Returns the Date value stored in the specified field name (using the Date class in the java.sql package, not java.util.Date) n getDouble(String)—Returns the double value stored in the specified field name n getFloat(String)—Returns the float value stored in the specified field name n getInt(String)—Returns the int value stored in the specified field name n getLong(String)—Returns the long value stored in the specified field name n getString(String)—Returns the String stored in the specified field name These are just the simplest methods available in the ResultSet interface. The methods you should use depend on the form that the field data takes in the database, although methods such as getString() and getInt() can be more flexible in the information they retrieve from a record. You also can use an integer as the argument to any of these methods, such as getString(5), instead of a string. The integer indicates which field to retrieve (1 for the first field, 2 for the second field, and so on). An SQLException is thrown if a database error occurs as you try to retrieve information from a resultset. You can call this exception’s getSQLState() and getErrorCode() methods to learn more about the error. After you have pulled the information you need from a record, you can move to the next record by calling the next() method of the ResultSet object. This method returns a false Boolean value when it tries to move past the end of a resultset. Normally, you can move through a resultset once from start to finish, after which you can’t retrieve its contents again. When you’re finished using a connection to a data source, you can close it by calling the connection’s close() method with no arguments. Listing 18.1 contains the CoalReporter application, which uses the JDBC-ODBC bridge and an SQL statement to retrieve some records from an energy database. Four fields are retrieved from each record indicated by the SQL statement: FIPS, Country, Year, and Anthracite Production. The resultset is sorted according to the Year field, and these fields are displayed to standard output. The JDBC-ODBC Bridge 493 18 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com LISTING 18.1 The Full Text of CoalReporter.java 1: import java.sql.*; 2: 3: public class CoalReporter { 4: public static void main(String[] arguments) { 5: String data = “jdbc:odbc:WorldEnergy”; 6: try { 7: Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 8: Connection conn = DriverManager.getConnection( 9: data, “”, “”); 10: Statement st = conn.createStatement(); 11: ResultSet rec = st.executeQuery( 12: “SELECT * “ + 13: “FROM Coal “ + 14: “WHERE “ + 15: “(Country=’” + arguments[0] + “‘) “ + 16: “ORDER BY Year”); 17: System.out.println(“FIPS\tCOUNTRY\t\tYEAR\t” + 18: “ANTHRACITE PRODUCTION”); 19: while(rec.next()) { 20: System.out.println(rec.getString(1) + “\t” 21: + rec.getString(2) + “\t\t” 22: + rec.getString(3) + “\t” 23: + rec.getString(4)); 24: } 25: st.close(); 26: } catch (SQLException s) { 27: System.out.println(“SQL Error: “ + s.toString() + “ “ 28: + s.getErrorCode() + “ “ + s.getSQLState()); 29: } catch (Exception e) { 30: System.out.println(“Error: “ + e.toString() 31: + e.getMessage()); 32: } 33: } 34: } This program must be run with a single argument specifying the Country field in the database from which to pull records, as in this example for the JDK: java CoalReporter Poland If the application were run with an argument of Poland, the output from the sample data- base would be the following: FIPS COUNTRY YEAR ANTHRACITE PRODUCTION PL Poland 1990 0.0 PL Poland 1991 0.0 PL Poland 1992 0.0 PL Poland 1993 174.165194805424 494 DAY 18: Accessing Databases with JDBC Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com PL Poland 1994 242.50849909616 PL Poland 1995 304.237935229728 PL Poland 1996 308.64718066784 PL Poland 1997 319.67029426312 PL Poland 1998 319.67029426312 Try running the program with other countries that produce anthracite, such as France, Swaziland, and New Zealand. For any country that has a space in the name, remember to put quotation marks around the country name when running the program. Writing Data to a Database Using SQL In the CoalReporter application, you retrieved data from a database using an SQL state- ment prepared as a string, like this: SELECT * FROM Coal WHERE (Country=’Swaziland’) ORDER BY YEAR 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. Prepared statements also have another advantage on Windows systems: They make it possible to write data to an Access data- base using the JDBC-ODBC driver. I’ve had little luck writing data from Java to Access using statements but can use prepared state- ments without any trouble. 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. The JDBC-ODBC Bridge 495 18 TIP Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Here’s an example for a connection object called cc: PreparedStatement ps = cc.prepareStatement( “SELECT * FROM Coal WHERE (Country=’?’) ORDER BY YEAR”); Here’s another example with more than one question mark: PreparedStatement ps = cc.prepareStatement( “INSERT INTO BOOKDATA VALUES(?, ?, ?, ?, ?, ?, ?)”); 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 meth- ods 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: n 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. n 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. n 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. n setBoolean(int, boolean)—Inserts a boolean value at the position indicated by the integer. n setByte(int, byte)—Inserts a byte value at the indicated position. n setBytes(int, byte[])—Inserts an array of bytes at the indicated position. 496 DAY 18: Accessing Databases with JDBC Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com n setDate(int, Date)—Inserts a Date object (from the java.sql package) at the indicated position. n setDouble(int, double)—Inserts a double value at the indicated position. n setFloat(int, float)—Inserts a float value at the indicated position. n setInt(int, int)—Inserts an int value at the indicated position. n setLong(int, long)—Inserts a long value at the indicated position. n setShort(int, short)—Inserts a short value at the indicated position. n 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! website. 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: http://quote.yahoo.com/q?s=sunw&d=v1 Below the price chart, you can find a Download Data link. Here’s what the link looks like for Sun Microsystems: http://download.finance.yahoo.com/d/quotes.csv?s=SUNW&f=sl1d1t1c1ohgv&e=.csv The JDBC-ODBC Bridge 497 18 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 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 Feb. 23, 2007: “SUNW”,6.27,”2/23/2007”,”4:00pm”,0.00,6.30,6.31,6.22,50254356 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: n The ticker symbol of a stock is taken as a command-line argument. n A QuoteData object is created with the ticker symbol as an instance variable called ticker. n The object’s retrieveQuote() method is called to download the stock data from Yahoo! and return it as a String. n 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, an Access 2000 database created to hold Yahoo!’s stock quote data, from the book’s website. Visit http://www.java21days.com and open the Day 18 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 18.2 into your editor and save the file as QuoteData.java. LISTING 18.2 The Full Text of QuoteData.java 1: import java.io.*; 2: import java.net.*; 3: import java.sql.*; 4: import java.util.*; 5: 6: public class QuoteData { 7: private String ticker; 8: 9: public QuoteData(String inTicker) { 498 DAY 18: Accessing Databases with JDBC Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... + “‘(501) 370 -80 00’, “ + “‘info@clintonpresidentialcenter.com’)”); 505 The JDBC-ODBC Bridge Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com LISTING 18. 3 59: 60 : 61 : 62 : 63 : 64 : 65 : 66 : 67 : 68 : 69 : 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80 : 81 : 82 : 83 : 84 : 85 : 86 : 87 : 88 : 89 : 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 1 06: 107: Continued result =... prep2.setString (8, fields [8] ); 18 500 DAY Simpo 18: Accessing Databases with JDBC PDF Merge and Split Unregistered Version - http://www.simpopdf.com LISTING 18. 2 59: 60 : 61 : 62 : 63 : 64 : 65 : 66 : 67 : 68 : 69 : 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80 : 81 : 82 : 83 : 84 : 85 : 86 : 87 : } Continued prep2.executeUpdate(); conn.close(); } catch (SQLException sqe) { System.out.println(“SQL Error: “ + sqe.getMessage()); } catch... JDBC-ODBC Bridge Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com LISTING 18. 2 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: Continued ticker = inTicker; } private String retrieveQuote() { StringBuffer buf = new StringBuffer(); try {... Microsoft Access and Java DB Using either Java Database Connectivity (JDBC) or a combination of JDBC and ODBC, you can incorporate existing data-storage solutions into your Java programs 18 5 08 DAY Simpo 18: Accessing Databases with JDBC PDF Merge and Split Unregistered Version - http://www.simpopdf.com You can connect to several different relational databases in your Java programs by using JDBC or ODBC... conn.prepareStatement( “INSERT INTO “ + “Stocks(ticker, price, quoteDate, change, open, “ + “high, low, volume) “ + “VALUES(?, ?, ?, ?, ?, ?, ?, ?)”); prep2.setString(1, fields[0]); prep2.setString(2, fields[1]); prep2.setString(3, fields[2]); prep2.setString(4, fields[4]); prep2.setString(5, fields[5]); prep2.setString (6, fields [6] ); prep2.setString(7, fields[7]); prep2.setString (8, fields [8] ); 18 500 DAY Simpo 18: Accessing... Presidents .java 1: import java. io.*; 2: import java. sql.*; 3: 4: public class Presidents { 5: String home, system; 6: 7: public Presidents() { 8: // set the database’s directory 9: home = System.getProperty(“user.home”, “.”); 18 504 DAY Simpo 18: Accessing Databases with JDBC PDF Merge and Split Unregistered Version - http://www.simpopdf.com LISTING 18. 3 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22:... (ClassNotFoundException cnfe) { System.out.println(cnfe.getMessage()); } } private String stripQuotes(String input) { StringBuffer output = new StringBuffer(); for (int i = 0; i < input.length(); i++) { if (input.charAt(i) != ‘\”’) { output.append(input.charAt(i)); } } return output.toString(); } public static void main(String[] arguments) { if (arguments.length < 1) { System.out.println(“Usage: java QuoteData tickerSymbol”);... 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 comma character (“,”) as the delimiter between each token The tokens are then stored in a String array with nine elements 501 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 Some versions of Access, including... (arguments[0].equals(“create”)) { prez.createDatabase(); } 18 5 06 DAY Simpo 18: Accessing Databases with JDBC PDF Merge and Split Unregistered Version - http://www.simpopdf.com LISTING 18. 3 1 08: 109: 110: 111: 112: } Continued if (arguments[0].equals(“read”)) { prez.readDatabase(); } } Using this application with another database and driver would require changes to lines 16, 19, 75, and 77 Java DB requires a system property, . 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). 242.5 084 990 961 6 PL Poland 1995 304.2379352297 28 PL Poland 19 96 3 08 .64 7 18 066 784 PL Poland 1997 319 .67 0294 263 12 PL Poland 19 98 319 .67 0294 263 12 Try running the program with other countries that produce anthracite,. position. n setFloat(int, float)—Inserts a float value at the indicated position. n setInt(int, int)—Inserts an int value at the indicated position. n setLong(int, long)—Inserts a long value at the indicated

Ngày đăng: 13/08/2014, 08:21

Từ khóa liên quan

Mục lục

  • Sams Teach Yourself Java 6 in 21 Days

    • Table of Contents

    • Introduction

      • How This Book Is Organized

      • Who Should Read This Book

      • Conventions Used in This Book

      • WEEK I: The Java Language

        • DAY 1: Getting Started with Java

          • The Java Language

          • Object-Oriented Programming

          • Objects and Classes

          • Attributes and Behavior

          • Organizing Classes and Class Behavior

          • Summary

          • Q&A

          • Quiz

          • Exercises

          • DAY 2: The ABCs of Programming

            • Statements and Expressions

            • Variables and Data Types

            • Comments

            • Literals

            • Expressions and Operators

            • String Arithmetic

            • Summary

Tài liệu cùng người dùng

Tài liệu liên quan