Basic jdbc access

From PTAGISWiki

Jump to: navigation, search


Here is the simplest known working Java app to read from the database:

import java.sql.* ;

class JDBCQuery
{
 public static void main( String args[] )
 {
  try
     {
      // Load the database driver
      //Class.forName( "ca.edbc.jdbc.EdbcDriver" ) ;
      Class.forName( "com.ingres.jdbc.IngresDriver" ) ;

      // Get a connection to the database
                //String URL = "jdbc:edbc://localhost:II7/blueback::ptagis3;tz=NA-Pacific";
                String URL = "jdbc:ingres://localhost:II7/blueback::ptagis3;tz=NA-Pacific";
                String USER = "webjsp";
                String PASS = "insert password here";
      Connection conn = DriverManager.getConnection( URL, USER, PASS);

      // Print all warnings
      for( SQLWarning warn = conn.getWarnings(); warn != null; warn = warn.getNextWarning() )
         {
          System.out.println( "SQL Warning:" ) ;
          System.out.println( "State  : " + warn.getSQLState()  ) ;
          System.out.println( "Message: " + warn.getMessage()   ) ;
          System.out.println( "Error  : " + warn.getErrorCode() ) ;
         }

      // Get a statement from the connection
      Statement stmt = conn.createStatement() ;

      // Execute the query
      ResultSet rs = stmt.executeQuery( "SELECT * FROM valid_species" ) ;

      // Loop through the result set
      while( rs.next() )
         System.out.println( rs.getString(1) ) ;

      // Close the result set, statement and the connection
      rs.close() ;
      stmt.close() ;
      conn.close() ;
     }
  catch( SQLException se )
     {
      System.out.println( "SQL Exception:" ) ;

      // Loop through the SQL Exceptions
      while( se != null )
         {
          System.out.println( "State  : " + se.getSQLState()  ) ;
          System.out.println( "Message: " + se.getMessage()   ) ;
          System.out.println( "Error  : " + se.getErrorCode() ) ;

          se = se.getNextException() ;
         }
     }
  catch( Exception e )
     {
      System.out.println( e ) ;
     }
 }
}
Personal tools