Dipl.-Inf. (FH) T. Mättig

29.03.2005

Get JDBC running

Abgelegt unter: — Thiemo Mättig @ 09:01

Here is a very simple JDBC example based on this JDBC introduction and this “Getting started with JDBC”. The following file is called JDBCExample.java:

/*
 * If this line is missing, errors like "cannot resolve
 * symbol Connection" and so on will happen. Additionally,
 * look at your JAVA_HOME and CLASSPATH environment
 * variables.
 */
import java.sql.*;
class JDBCExample
{
  /*
   * This is a plain script without any classes and objects.
   */
  public static void main(String args[])
  {
    System.out.println("JDBC example starts...");
    /*
     * If something fails, try will catch the errors and
     * handle or simply display them in the catch part.
     */
    try
    {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      /*
       * Connect to the Data Source Name prepared in "ODBC
       * Data Sources" in the Windows control panel. Login
       * name and passwort are empty.
       */
      Connection connection = DriverManager.getConnection(
        "jdbc:odbc:database",
        "",
        "");
      Statement statement = connection.createStatement();
      /*
       * Here is the table name we want to access.
       */
      ResultSet result = statement.executeQuery
        ("SELECT * FROM `dates`");
      while (result.next())
      {
        /*
         * These are the table columns we want to see.
         */
        System.out.println("id: " +
          result.getInt("id"));
        System.out.println("text: " +
          result.getString("text"));
      }
    }
    catch (Exception e)
    {
      System.out.println(e);
    }
  }
}

To get this script running, you may use the following run.bat batch file:

@echo off
if "%1" == "" goto error
rem Enable and adjust these lines if some paths are missing.
rem SET JAVA_HOME = C:\Programme\Sun\jdk1.5.0_02
rem SET CLASSPATH = C:\Programme\Sun\jdk1.5.0_02\jre\lib\rt.jar;%CLASSPATH%
%JAVA_HOME%\bin\javac %1.java
%JAVA_HOME%\bin\java %1
goto end
:error
echo Java source file name missing. Example:
echo run Example
echo (Without the .java file name extension.)
:end

Additionally, you need a Microsoft Access database file (e.g. database.mdb) and a ODBC data source called database. The Java script tries to access a table called dates with two columns id and text.

Download the sources and database here.

Kommentare

Noch keine Beiträge.

Einen Kommentar abgeben

Sorry, das Kommentarformular ist derzeit abgeschaltet.

Powered by WordPress