Java Issuing Queries and Retrieving Results
2.5.8 Java
The JDBC int erface provides specific obj ect t ypes for t he various phases of query processing. Queries are issued in JDBC by passing SQL st rings t o Java obj ect s of one t ype. The result s, if t here are any, are ret urned as obj ect s of anot her t ype. Problem s t hat occur while accessing t he dat abase cause except ions t o be t hrown. To issue a query, t he first st ep is t o get a Statement obj ect by calling t he createStatement m et hod of your Connection obj ect : Statement s = conn.createStatement ; Then use t he Statement obj ect t o send t he query t o t he server. JDBC provides several m et hods for doing t his. Choose t he one t hat s appropriat e for t he t ype of st at em ent you want t o issue: executeUpdate for st at em ent s t hat dont ret urn a result set , executeQuery for st at em ent s t hat do, and execute when you dont know. The executeUpdate m et hod sends a query t hat generat es no result set t o t he server and ret urns a count indicat ing t he num ber of rows t hat were affect ed. When youre done wit h t he st at em ent obj ect , close it . The following exam ple illust rat es t his sequence of event s: try { Statement s = conn.createStatement ; int count = s.executeUpdate DELETE FROM profile WHERE cats = 0; s.close ; close statement System.out.println count + rows were deleted; } catch Exception e { Cookbook.printErrorMessage e; } For st at em ent s t hat ret urn a result set , use executeQuery . Then get a result set obj ect and use it t o ret rieve t he row values. When youre done, close bot h t he result set and st at em ent obj ect s: try { Statement s = conn.createStatement ; s.executeQuery SELECT id, name, cats FROM profile; ResultSet rs = s.getResultSet ; int count = 0; while rs.next loop through rows of result set { int id = rs.getInt 1; extract columns 1, 2, and 3 String name = rs.getString 2; int cats = rs.getInt 3; System.out.println id: + id + , name: + name + , cats: + cats; ++count; } rs.close ; close result set s.close ; close statement System.out.println count + rows were returned; } catch Exception e { Cookbook.printErrorMessage e; } The ResultSet obj ect ret urned by t he getResultSet m et hod of your Statement obj ect has a num ber of m et hods of it s own, such as next t o fet ch row s and various get XXX m et hods t hat access colum ns of t he current row. I nit ially t he result set is posit ioned j ust before t he first row of t he set . Call next t o fet ch each row in succession unt il it ret urns false, indicat ing t hat t here are no m ore rows. To det erm ine t he num ber of rows in a result set , count t hem yourself, as shown in t he preceding exam ple. Colum n values are accessed using m et hods such as getInt , getString , getFloat , and getDate . To obt ain t he colum n value as a generic obj ect , use getObject . The get XXX calls can be invoked wit h an argum ent indicat ing eit her colum n posit ion beginning at 1, not 0 or colum n nam e. The previous exam ple shows how t o ret rieve t he id , name , and cats colum ns by posit ion. To access colum ns by nam e inst ead, t he row- fet ching loop of t hat exam ple can be rewrit t en as follows: while rs.next loop through rows of result set { int id = rs.getInt id; String name = rs.getString name; int cats = rs.getInt cats; System.out.println id: + id + , name: + name + , cats: + cats; ++count; } You can ret rieve a given colum n value using any get XXX call t hat m akes sense for t he colum n t ype. For exam ple, you can use getString t o ret rieve any colum n value as a st r ing: String id = rs.getString id; String name = rs.getString name; String cats = rs.getString cats; System.out.println id: + id + , name: + name + , cats: + cats; Or you can use getObject t o ret rieve values as generic obj ect s and convert t he values as necessary. The following code uses toString t o convert obj ect values t o print able form : Object id = rs.getObject id; Object name = rs.getObject name; Object cats = rs.getObject cats; System.out.println id: + id.toString + , name: + name.toString + , cats: + cats.toString ; To find out how m any colum ns are in each row, access t he result set s m et adat a. The following code uses t he colum n count t o print each rows colum ns as a com m a- separat ed list of values: try { Statement s = conn.createStatement ; s.executeQuery SELECT FROM profile; ResultSet rs = s.getResultSet ; ResultSetMetaData md = rs.getMetaData ; get result set metadata int ncols = md.getColumnCount ; get column count from metadata int count = 0; while rs.next loop through rows of result set { for int i = 0; i ncols; i++ loop through columns { String val = rs.getString i+1; if i 0 System.out.print , ; System.out.print val; } System.out.println ; ++count; } rs.close ; close result set s.close ; close statement System.out.println count + rows were returned; } catch Exception e { Cookbook.printErrorMessage e; } The t hird JDBC query- execut ing m et hod, execute , works for eit her t ype of query. I t s part icularly useful when you receive a query st ring from an ext ernal source and dont know whet her or not it generat es a result set . The ret urn value from execute indicat es t he query t ype so t hat you can process it appropriat ely: if execute ret urns t rue, t here is a result set , ot herwise not . Typically youd use it som et hing like t his, where queryStr represent s an arbit rary SQL st at em ent : try { Statement s = conn.createStatement ; if s.execute queryStr { there is a result set ResultSet rs = s.getResultSet ; ... process result set here ... rs.close ; close result set } else { there is no result set, just print the row count System.out.println s.getUpdateCount + rows were affected; } s.close ; close statement } catch Exception e { Cookbook.printErrorMessage e; } Closing JDBC Statement and Result Set Objects The JDBC query- issuing exam ples in t his sect ion close t he st at em ent and result set obj ect s explicit ly when t hey are done wit h t hose obj ect s. Som e Java im plem ent at ions close t hem aut om at ically when you close t he connect ion. However, buggy im plem ent at ions m ay fail t o do t his properly, so it s best not t o rely on t hat behavior. Close t he obj ect s yourself when youre done wit h t hem t o avoid difficult ies.2.6 Moving Around Within a Result Set
Parts
» O'Reilly-MySQL.Cookbook.eBook-iNTENSiTY. 4810KB Mar 29 2010 05:03:43 AM
» Introduction Using the mysql Client Program
» Problem Solution Discussion Setting Up a MySQL User Account
» Problem Solution Discussion Starting and Terminating mysql
» Problem Solution Discussion Specifying Connection Parameters by Using Option Files
» Problem Solution Discussion Mixing Command-Line and Option File Parameters
» Problem Solution Discussion What to Do if mysql Cannot Be Found
» Problem Solution Discussion Setting Environment Variables
» Problem Solution Discussion Repeating and Editing Queries
» Problem Solution Discussion Preventing Query Output from Scrolling off the Screen
» Problem Solution Discussion Specifying Arbitrary Output Column Delimiters
» Problem Solution Discussion Logging Interactive mysql Sessions
» Discussion Using mysql as a Calculator
» Writing Shell Scripts Under Unix
» Writing Shell Scripts Under Windows
» MySQL Client Application Programming Interfaces
» Perl Connecting to the MySQL Server, Selecting a Database, and Disconnecting
» PHP Connecting to the MySQL Server, Selecting a Database, and Disconnecting
» Python Connecting to the MySQL Server, Selecting a Database, and Disconnecting
» Java Connecting to the MySQL Server, Selecting a Database, and Disconnecting
» Problem Solution Discussion Checking for Errors
» Python Java Checking for Errors
» Problem Solution Discussion Writing Library Files
» Python Writing Library Files
» SQL Statement Categories Issuing Queries and Retrieving Results
» Perl Issuing Queries and Retrieving Results
» Python Issuing Queries and Retrieving Results
» Java Issuing Queries and Retrieving Results
» Problem Solution Discussion Moving Around Within a Result Set
» Problem Solution Discussion Using Prepared Statements and Placeholders in Queries
» Perl Using Prepared Statements and Placeholders in Queries
» PHP Python Java Using Prepared Statements and Placeholders in Queries
» Problem Solution Discussion Including Special Characters and NULL Values in Queries
» Perl Including Special Characters and NULL Values in Queries
» PHP Including Special Characters and NULL Values in Queries
» Python Java Including Special Characters and NULL Values in Queries
» PHP Python Java Handling NULL Values in Result Sets
» Problem Solution Discussion Writing an Object-Oriented MySQL Interface for PHP
» Class Overview Writing an Object-Oriented MySQL Interface for PHP
» Connecting and Disconnecting Writing an Object-Oriented MySQL Interface for PHP
» Error Handling Issuing Queries and Processing the Results
» Quoting and Placeholder Support
» Problem Solution Discussion Ways of Obtaining Connection Parameters
» Getting Parameters from the Command Line
» Getting Parameters from Option Files
» Conclusion and Words of Advice
» Problem Solution Discussion Avoiding Output Column Order Problems When Writing Programs
» Problem Solution Discussion Using Column Aliases to Make Programs Easier to Write
» Problem Solution Discussion Selecting a Result Set into an Existing Table
» Problem Solution Discussion Creating a Destination Table on the Fly from a Result Set
» Problem Solution Discussion Moving Records Between Tables Safely
» Problem Solution Discussion Cloning a Table Exactly
» Problem Solution Discussion Generating Unique Table Names
» Problem Solution Discussion Using TIMESTAMP Values
» Problem Solution Discussion Using ORDER BY to Sort Query Results
» Solution Discussion Working with Per-Group and Overall Summary Values Simultaneously
» Problem Solution Discussion Changing a Column Definition or Name
» Problem Solution Discussion Changing a Table Type
» Problem Solution Discussion Adding Indexes
» Introduction Obtaining and Using Metadata
» Problem Solution Discussion Perl PHP
» Problem Solution Discussion Perl
» PHP Obtaining Result Set Metadata
» Python Obtaining Result Set Metadata
» Java Obtaining Result Set Metadata
» Using Result Set Metadata to Get Table Structure
» Problem Solution Discussion Database-Independent Methods of Obtaining Table Information
» Problem Solution Discussion Displaying Column Lists Interactive Record Editing
» Mapping Column Types onto Web Page Elements Adding Elements to ENUM or SET Column Definitions
» Selecting All Except Certain Columns
» Problem Solution Discussion Listing Tables and Databases
» Problem Solution Writing Applications That Adapt to the MySQL Server Version
» Discussion Writing Applications That Adapt to the MySQL Server Version
» Problem Solution Discussion Determining Which Table Types the Server Supports
» General Import and Export Issues
» Problem Solution Discussion Importing Data with LOAD DATA and mysqlimport
» Problem Solution Discussion Specifying the Datafile Location
» Problem Solution Discussion Specifying the Datafile Format
» Problem Solution Discussion Dealing with Quotes and Special Characters
» Problem Solution Discussion Handling Duplicate Index Values
» Problem Solution Discussion Getting LOAD DATA to Cough Up More Information
» Problem Solution Discussion Dont Assume LOAD DATA Knows More than It Does
» Problem Solution Discussion Skipping Datafile Columns
» Problem Solution Discussion Exporting Query Results from MySQL
» Using the mysql Client to Export Data
» Problem Solution Discussion Exporting Tables as Raw Data
» Problem Solution Discussion Exporting Table Contents or Definitions in SQL Format
» Problem Solution Discussion Copying Tables or Databases to Another Server
» Problem Solution Discussion Writing Your Own Export Programs
» Problem Solution Discussion Converting Datafiles from One Format to Another
» Problem Solution Discussion Extracting and Rearranging Datafile Columns
» Problem Solution Discussion Validating and Transforming Data
» Writing an Input-Processing Loop Putting Common Tests in Libraries
» Problem Solution Discussion Validation by Pattern Matching
» Problem Solution Discussion Using Patterns to Match Numeric Values
» Problem Solution Discussion Using Patterns to Match Dates or Times
» See Also Using Patterns to Match Dates or Times
» Problem Solution Discussion Using Patterns to Match Email Addresses and URLs
» Problem Solution Discussion Validation Using Table Metadata
» Problem Solution Discussion Issue Individual Queries Construct a Hash from the Entire Lookup Table
» Use a Hash as a Cache of Already-Seen Lookup Values
» Problem Solution Discussion Converting Two-Digit Year Values to Four-Digit Form
» Problem Solution Discussion Performing Validity Checking on Date or Time Subparts
» Problem Solution Discussion Writing Date-Processing Utilities
» Problem Solution Discussion Performing Date Conversion Using SQL
» Problem Solution Discussion Guessing Table Structure from a Datafile
» Problem Solution Discussion A LOAD DATA Diagnostic Utility
» Problem Solution Discussion Exchanging Data Between MySQL and Microsoft Access
» Problem Solution Discussion Exchanging Data Between MySQL and Microsoft Excel
» Problem Solution Discussion Exchanging Data Between MySQL and FileMaker Pro
» Problem Solution Discussion Importing XML into MySQL
» Epilog Importing and Exporting Data
» Introduction Generating and Using Sequences
» Problem Solution Discussion Using AUTO_INCREMENT To Set Up a Sequence Column
» Problem Solution Discussion Choosing the Type for a Sequence Column
» Problem Solution Discussion Ensuring That Rows Are Renumbered in a Particular Order
» Problem Solution Discussion Managing Multiple Simultaneous AUTO_INCREMENT Values
» Problem Solution Discussion Using AUTO_INCREMENT Values to Relate Tables
» Problem Solution Discussion Generating Repeating Sequences
» Problem Solution Discussion See Also
» Performing a Related-Table Update Using Table Replacement
» Performing a Related-Table Update by Writing a Program
» Performing a Multiple-Table Delete by Writing a Program
» Problem Solution Discussion Dealing with Duplicates at Record-Creation Time
» Problem Solution Discussion Using Transactions in Perl Programs
» Problem Solution Discussion Using Transactions in Java Programs
» Problem Solution Discussion Using Alternatives to Transactions
» Grouping Statements Using Locks
» Rewriting Queries to Avoid Transactions
» Introduction Introduction to MySQL on the Web
» Problem Solution Discussion Basic Web Page Generation
» Problem Solution Discussion Using Apache to Run Web Scripts
» Problem Solution Discussion Using Tomcat to Run Web Scripts
» Installing the mcb Application
» Installing the JSTL Distribution
» Problem Solution Discussion Encoding Special Characters in Web Output
» General Encoding Principles Encoding Special Characters in Web Output
» Encoding Special Characters Using Web APIs
» Introduction Incorporating Query Results into Web Pages
» Problem Solution Discussion Creating a Navigation Index from Database Content
» Creating a Multiple-Page Navigation Index
» Problem Solution Discussion Storing Images or Other Binary Data
» Storing Images with LOAD_FILE Storing Images Using a Script
» Problem Solution Discussion Retrieving Images or Other Binary Data
» Problem Solution Discussion Serving Banner Ads
» Problem Solution Discussion Serving Query Results for Download
» Introduction Processing Web Input with MySQL
» Problem Solution Discussion Creating Forms in Scripts
» Problem Solution Discussion Creating Multiple-Pick Form Elements from Database Content
» Problem Solution Discussion Loading a Database Record into a Form
» Problem Solution Discussion Collecting Web Input
» Web Input Extraction Conventions Perl
» Problem Solution Discussion Validating Web Input
» Problem Solution Discussion Using Web Input to Construct Queries
» Problem Solution Discussion Processing File Uploads
» Perl Processing File Uploads
» Problem Solution Discussion Performing Searches and Presenting the Results
» Problem Solution Discussion Generating Previous-Page and Next-Page Links
» Paged Displays with Previous-Page and Next-Page Links
» Paged Displays with Links to Each Page
» Problem Solution Discussion Web Page Access Counting
» Problem Solution Discussion Web Page Access Logging
» Problem Solution Discussion Setting Up Database Logging
» Other Logging Issues Using MySQL for Apache Logging
» Session Management Issues Introduction
» Problem Solution Discussion Installing Apache::Session
» The Apache::Session Interface
» A Sample Application Using MySQL-Based Sessions in Perl Applications
» Problem Solution Discussion The PHP 4 Session Management Interface
» Specifying a User-Defined Storage Module
» Problem Solution Discussion Using MySQL for Session BackingStore with Tomcat
» The Servlet and JSP Session Interface A Sample JSP Session Application
Show more