JDBC-Beispiele


Select-Beispiel

import java.net.URL;
import java.sql.*;

class Select {
  public static void main(String argv[]) {
    try {
        String url = "jdbc:odbc:rechner";

        Connection con = DriveManager.getConnection(url, "mha", "");

        Statement stmt = con.createStatement();
        ResultSet rs   = stmt.Query("SELECT a,b,c,d,key FROM Tabelle1");

        System.out.println("Das Ergebnis: ");
        while (rs.next()) {
          int a      = rs.getInteger(1);
          Numeric b  = rs.getNumeric(2);
          char c[]   = rs.getVarChar(3).toCharArray();
          boolean d  = rs.getBit(4);
          String key = rs.getVarChar(5);

          System.out.print("  key=" + key);
          System.out.print("  a  =" + a  );
          System.out.print("  b  =" + b  );
          System.out.print("  c  =");
          for (int i=0; i < c.length(); i++) {
            System.out.print(c[i]);
          }
          System.out.print("  d  =" + d  );
          System.out.print("\n");
        }

        stmt.close();
        con.close();
    } catch (java.lang.Exception e) {
        e.printStackTrace();
        System.out.println("Fehler: " + e.getMessage());
    }
  }
}

Update-Beispiel

import java.net.URL;
import java.sql.*;

class Update {
  public static void main(String argv[]) {
    try {
        String url = "jdbc:odbc:rechner";

        Connection con = DriverManager.getConnection(url, "mha", "");

        PreparedStatement stmt = con.prepareStatement("UPDATE Tabelle1 SET a = ? WHERE key = ?");

        stmt.setInteger(1, 34);
        stmt.setVarChar(2, "count");
        stmt.executeUpdate();
        System.out.println("Updated \"count\" row OK.");

        // reuse 1st parameter
        stmt.setVarChar(2, "mirror");
        stmt.executeUpdate();
        System.out,println("Updated \"mirror\" row OK.");

        stmt.close();
        con.close();
    } catch (java.lang.Exception e) {
        e.printStackTrace();
        System.out.println("Fehler: " + e.getMessage());
    }
  }
}

Michael Hasenstein; April 1996