★ wanayoo — archive 1999 http://wdvl.com/Authoring/DB/Intro/jdbc_query.htmlNouvelle recherche | Portail wanayoo

Top Ten Internet Stocks logo

internet.com
Join the free
WDVL newsletter!

home

Using JDBC to Query a Database

November 23, 1998

Once you have the statement handle, it is very easy to query the database. To do so, you use the statement handle to send standard SQL to the database and then parse through the results returned from the database. Take a look at the following example.

Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Connection jdbcConnection = 
	         DriverManager.getConnection
                 (jdbc:odbc:Access);
Statement sqlStatement = jdbcConnection.createStatement();

        // We have seen all of the above before.  
        // No surprises so far.  in the next line, we
        // will simply create a string of SQL.  

String sql = "SELECT * FROM CUSTOMERS";

        // Next we will attempt to send the SQL command to
        // the database.  If it works, the database will 
        // return to us a set of results that JDBC will 
        // store in a ResultSet object.

try
  {
  ResultSet results = sqlStatement.executeQuery(sql);

        // We simply go through the ResultSet object
        // one element at a time and print out the 
        // fields.  In this example, we assume that
        // the result set will contain three fields

  while (results.next())
    {
    System.our.println("Field One: " + 
                       results.getString(1) +
                       "Field Two: " + 
                       results.getString(2) +
                       "Field Three: " + 
                       results.getString(3));
    }
  }

        // If there was a problem sending the SQL, 
        // we will get this error.

catch (Exception e)
  {
  System.out.println("Problem with Sending Query: " + e);
  }

Note that if the field is an Integer, you should use the getInt() method in ResultSet instead of getString()

Using JDBC to Connect to a Database
Introduction to Databases for the Web | Table of Contents
Using JDBC to Modify a Database

Up to => Home / Authoring / DB / Intro

Instantly look up a "techie" word using Webopedia!!


internet.com
e-commerce
WebDeveloper Network


Get Press Exposure!

Copyright 1999 internet.com Corporation. Legal Notices. Privacy Policy.

www.internet.com