"JDBCDemo" Java class

A very simple demo showing the minimum code needed to use JDBC.

This is the smallest, simplest standalone JDBC application I could come up with. The JDBC class name, URL, and userid/password are left blank - there's no way I can know how your particular database environment is set up so I can't give that to you, you have to figure it out.

Note: the package statement requires the class file to be located at org/white_mountain/JDBCDemo.class, relative to any directory in your CLASSPATH, or the Java class loader won't be able to find it. If this confuses you then just remove it. Otherwise, create that directory structure (you are using packages to help manage your Java source files, right?? :) ) and stash it in with all the rest of your stuff.

The source code is available in a standalone document (easier to save than cutting and pasting into a text editor) and below. (The .class file is useless since you have to edit the source file to include your DB's info and then compile it yourself, so there's no reason for me to make it available.)

Good luck!

/*
  This program:
  - was written by Jamie Flournoy (jamie@white-mountain.org)
  - is available from http://www.white-mountain.org/jdbc/JDBCDemo.shtml
  - is in the public domain - go ahead and use it for whatever you want.
*/

package org.white_mountain;

import java.sql.*;

public class JDBCDemo
{
  public static void main(String argv[]) throws Exception
    {
      // The JDBC driver class and URL depend on the driver you are
      // using (read the driver documentation). The URL, userid and
      // password depend on your DB installation (ask your DBA or use
      // the DB's admin tools to set up a user account for yourself).
      String jdbc_driver_class = "";
      String jdbc_url          = "";
      String db_userid         = "";
      String db_password       = "";
      
      // This statement always works on Oracle; for other DB's change
      // this to something more appropriate
      String sql_statement     = "select * from dual";
      
      try
	{
	  Class.forName(jdbc_driver_class);
	  
	  Connection con = DriverManager.getConnection(jdbc_url, db_userid, db_password);
	  Statement stmt = con.createStatement();
	  
	  ResultSet rs = stmt.executeQuery(sql_statement);
	  
	  int col_count = rs.getMetaData().getColumnCount();
	  int col;
	  while(rs.next())
	    {
	      // column numbers start with 1 not 0
	      for (col = 1 ; col <= col_count; col++) 
		{
		  System.out.print( rs.getString(col) + "\t");
		}
	      System.out.print("\n");
	    }
	  
	  rs.close();
	  stmt.close();
	  con.close();
	}
      catch(Exception e) 
	{ 
	  System.err.println("Something barfed: "+e);
	}
    }
}