Benutzer-Werkzeuge

Webseiten-Werkzeuge


playgrounds:processing

Zugriff auf die Datenbank

In Processing können neben vielen existierenden Libraries auch die „klassischen“ Java Bibliotheken wie JDBC Treiber verwendet werden.

Processing läuft im Prinzip in der Java Applet Umgebung, d.h. die eigentliche Processing Main Klasse ist vom Applet abgeleitet. Die setup() Methode wird einmalig aufgerufen, hier wird alles Notwendige für den Start der Applikation verarbeitet. Die draw() Methode „zeichnet“ den Frame immer wieder neu.

Für „andere Datenbank“ steht die Library „SQLibrary“ unter http://processing.org/reference/libraries/ zur Verfügung, dort könnte bestimmt auch die Oracle JDBC Lib mit „eingebaut“ werden.

Für den Aufbau einer eigenen Library : http://code.google.com/p/processing/wiki/LibraryBasics

In Folge aber eine Lösung für das eigene Einbinden der JDBC Library von Oracle in die Processing IDE.

Vorbereitung

Die IDE sucht sich alle *.jar Dateien im Library Home Verzeichnis der IDE, unter Windows ist das in meiner Umgebung bei einer Default Installation „C:\Users\gpipperr\Documents\Processing\libraries“

Dort die folgende Struktur anlegen „.\ojdbc6\library“ und die ojdbc6.jar dort ablegen.

Danach die IDE neustarten.

Damit die IDE von Processing die Library erkennt, MUSS der Name des Lib Verzeichnisse gleich einem der Jar Files in dem <jar_name>\library\<jar_name>.jar sein! Wie in unseren Beispiel: .\ojdbc6\library\ojdbc6.jar !
Einbinden der JDBC library

Nach dem Neustart der IDE kann die JDBC Lib wie gewohnt in Java eingebunden werden.

In der Start Methode kann die Verbindung zur Datenbank geöffnet werden, in der draw Methode werden die Daten abgerufen.

Aber wie schließen wir die Verbindung zur Datenbank wenn wir die Applikation beenden? Die final() Methode von Applet würde sich eigenen, sollte aber nicht so einfach überschrieben werden. Wir können auch einen eigen Erweiterung für Processing schreiben und dort die dispose() Methode erstellen (siehe Beispiel auf der LibraryBasics Website).

Alternativ wird als Lösung wird ein Event Händler an den „Shutdown“ Event der Applikation „angehängt“, dort kann die Datenbank Verbindung sicher geschlossen werden und es kann auf den globalen DB Connect zugriffen werden.

Beispiel für den ShutdownHook:

...
java.sql.Connection con=null;
....
 
void setup() {
...
 
  registerShutdownHook ();
...  
 
}
 
...
 
private void registerShutdownHook () {
  Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    public void run () {
      System.out.println("Shutdown in progress ..");
      try {
          //Datenbankverbindung schließen
          if (con.isClosed() != false) {
             con.close();      
             System.out.println("DB Connection closed");
          }
          // Orginal Stop aufrufen
          stop();
      } 
      catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }
  ));
}

Ein komplettes Beispiel: In diesen Beispiel wird der Einsatz des DB Connects und eine Abfrage pro draw gezeigt, allerdings ist die graphische Ausgabe hier nur ein nicht ganz erstgemeinter Test!

So steht das ganz auf dem Kopf und die Skalierung ist mehr als fragwürdig .-).

import java.sql.*;
import oracle.jdbc.driver.*;
 
int bColor=0;
float x=0;
float value=0;
 
float value_now=0;
float value_before=0;
 
int fa=100;
 
java.sql.Connection con=null;
Statement stmt=null;
 
void setup() {
 
  size(1000, 400);
 
  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
  // register the exit handler to close the DB connection!
  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  prepareExitHandler ();
 
 
 
  // jdbc Parameter and Connectstring
  String url      = "jdbc:oracle:thin:@localhost:1521:GPI";
  String user     = "system";
  String password = "oracle";
 
 // open Connection
  try {
    //Oracle JDBC Driver
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    // Connect
    con = DriverManager.getConnection(url, user, password);
  }
  catch (SQLException ex) {
    System.err.println("SQLException : " + ex.getMessage());
  }
}
 
//
// Main - Draw the DB Statistics
// 
 
void draw() {
 
  // query on value from the DB statistic
  String query = "select value from v$sysstat where name ='bytes sent via SQL*Net to client' ";
 
  try {
 
    //create Statement
    stmt = con.createStatement();
 
    //execute query and create  Resultset  
    ResultSet rs = stmt.executeQuery(query);
 
    //get the Metainformation of the resultste
    ResultSetMetaData rsmd = rs.getMetaData();
 
    //print the column names
    // only a example
    /*
    int ncount = rsmd.getColumnCount();
    for (int i=1; i<=ncount; i++) {
      if (i!=ncount){
          System.out.print(rsmd.getColumnName(i) + "::");
      }
      else{
        System.out.println(rsmd.getColumnName(i));
      }
    }
    */
 
    // read the first value from the resultset
    while (rs.next ()) {
      value_now=rs.getInt(1);
    }
 
    //close the statement
    stmt.close();
  }
  catch (SQLException ex) {
    System.err.println("SQLException : " + ex.getMessage());
  }
 
  //-------------- print the value  on the screen -------------
  // very simple version to show something from the DB
  // .-)
 
  // the total value of a DB statisc is not very usefull, we need the differenz from the last value to now 
  // to the the runtime behavior of the application
 
  value=value_now-value_before;
  // Scale factor
  double t= Math.round( log10((double)value) );
  double  q=Math.pow(10, t);
  // Scaled value
  value=(height*value) / (float) q;
  // draw on the screen also a value for 0
  if (value > 400){
    // why 101?
    // we move the plot for 100px .-)
    value=101;
  }
 
  // movment ot the right
  x=x+1;
 
  //color changes after reaching the right border
  fill(fa, 0, 0);
  // draw a bubble
  ellipse(x, value-100, 5, 5);
 
  println("Scaled value :: "+value);
 
  // start again from the left
  if ( x > width ) {
    x=0;  
    // new color
    fa+=20;
    System.out.println("Info -- set fa to :: " +fa);
    if (fa > 254) { 
      fa=0;
    }
  }
  // store new value as old for next round
  value_before=value_now;
}
 
// 
// helper funktio for the count of dezimals 
//
double log10(double val) {
  return Math.log(val) / Math.log(10);
}
 
 
// 
// Check for open DB Connection and close if nessesary
// Must be initialised in the setup Section
// 
 
private void prepareExitHandler () {
  Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    public void run () {
      System.out.println("SHUTDOWN HOOK");
 
      try {
        //close DB connection
        if (con.isClosed() != false ) {
          con.close();      
          System.out.println("DB Connection closed");
        }   
        stop();
      } 
      catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }
  ));
}
Diese Website verwendet Cookies. Durch die Nutzung der Website stimmen Sie dem Speichern von Cookies auf Ihrem Computer zu. Außerdem bestätigen Sie, dass Sie unsere Datenschutzbestimmungen gelesen und verstanden haben. Wenn Sie nicht einverstanden sind, verlassen Sie die Website.Weitere Information
"Autor: Gunther Pipperr"
playgrounds/processing.txt · Zuletzt geändert: 2013/04/09 20:43 von gpipperr