2 * put your module comment here
10 import freemarker.template.*;
11 import com.javaexchange.dbConnectionBroker.*;
12 import mir.storage.StorageObject;
18 * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
19 * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
20 * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
21 * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
22 * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
28 public class Database implements StorageObject {
30 protected DbConnectionBroker myBroker;
31 protected String theTable;
32 protected String theCoreTable=null;
33 protected String thePKeyName="id";
34 protected int thePKeyType;
35 protected boolean evaluatedMetaData=false;
36 protected ArrayList metadataFields,metadataLabels,metadataNotNullFields;
37 protected int[] metadataTypes;
38 protected Class theEntityClass;
39 protected StorageObject myselfDatabase;
40 protected HashMap cache;
41 protected SimpleList popupCache=null;
42 protected boolean hasPopupCache = false;
43 protected SimpleHash hashCache=null;
44 protected boolean hasTimestamp=true;
45 private String database_driver;
46 private String database_url;
47 private int defaultLimit;
48 protected DatabaseAdaptor theAdaptor;
49 protected Logfile theLog;
50 //protected Connection con;
53 * Kontruktor bekommt den Filenamen des Konfigurationsfiles übergeben.
54 * Aus diesem file werden <code>Database.Logfile</code>,
55 * <code>Database.Username</code>,<code>Database.Password</code>,
56 * <code>Database.Host</code> und <code>Database.Adaptor</code>
57 * ausgelesen und ein Broker für die Verbindugen zur Datenbank
60 * @param String confFilename Dateiname der Konfigurationsdatei
62 public Database() throws StorageObjectException {
63 theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Database.Logfile"));
64 String database_username=MirConfig.getProp("Database.Username");
65 String database_password=MirConfig.getProp("Database.Password");
66 String database_host=MirConfig.getProp("Database.Host");
67 String theAdaptorName=MirConfig.getProp("Database.Adaptor");
69 theEntityClass = Class.forName("mir.entity.GenericEntity");
70 theAdaptor = (DatabaseAdaptor)Class.forName(theAdaptorName).newInstance();
71 defaultLimit = Integer.parseInt(MirConfig.getProp("Database.Limit"));
72 database_driver=theAdaptor.getDriver();
73 database_url=theAdaptor.getURL(database_username,database_password,database_host);
74 theLog.printDebugInfo("adding Broker with: " +database_driver+":"+database_url );
75 MirConfig.addBroker(database_driver,database_url);
76 myBroker=MirConfig.getBroker();
79 theLog.printError("Bei Konstruktion von Database() with " + theAdaptorName + " -- " +e.toString());
80 throw new StorageObjectException(e.toString());
85 * Liefert die Entity-Klasse zurück, in der eine Datenbankzeile gewrappt
86 * wird. Wird die Entity-Klasse durch die erbende Klasse nicht überschrieben,
87 * wird eine mir.entity.GenericEntity erzeugt.
89 * @return Class-Objekt der Entity
91 public java.lang.Class getEntityClass () {
92 return theEntityClass;
96 * Liefert die Standardbeschränkung von select-Statements zurück, also
97 * wieviel Datensätze per Default selektiert werden.
99 * @return Standard-Anzahl der Datensätze
101 public int getLimit () {
106 * Liefert den Namen des Primary-Keys zurück. Wird die Variable nicht von
107 * der erbenden Klasse überschrieben, so ist der Wert <code>PKEY</code>
108 * @return Name des Primary-Keys
110 public String getIdName () {
115 * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
117 * @return Name der Tabelle
119 public String getTableName () {
124 * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
125 * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet wird.
126 * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
130 public String getCoreTable(){
131 if (theCoreTable!=null) return theCoreTable;
132 else return theTable;
136 * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
137 * @return int-Array mit den Typen der Felder
138 * @exception StorageObjectException
140 public int[] getTypes () throws StorageObjectException {
141 if (metadataTypes == null)
143 return metadataTypes;
147 * Liefert eine Liste der Labels der Tabellenfelder
148 * @return ArrayListe mit Labeln
149 * @exception StorageObjectException
151 public ArrayList getLabels () throws StorageObjectException {
152 if (metadataLabels == null)
154 return metadataLabels;
158 * Liefert eine Liste der Felder der Tabelle
159 * @return ArrayList mit Feldern
160 * @exception StorageObjectException
162 public ArrayList getFields () throws StorageObjectException {
163 if (metadataFields == null)
165 return metadataFields;
170 * Gets value out of ResultSet according to type and converts to String
171 * @param inValue Wert aus ResultSet.
172 * @param aType Datenbanktyp.
173 * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
174 * dann /unsupported value/
176 private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
177 String outValue = null;
181 case java.sql.Types.BIT:
182 outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
184 case java.sql.Types.INTEGER:case java.sql.Types.SMALLINT:case java.sql.Types.TINYINT:case java.sql.Types.BIGINT:
185 int out = rs.getInt(valueIndex);
187 outValue = new Integer(out).toString();
189 case java.sql.Types.NUMERIC:
190 long outl = rs.getLong(valueIndex);
192 outValue = new Long(outl).toString();
194 case java.sql.Types.REAL:
195 float tempf = rs.getFloat(valueIndex);
199 int tempf_int = (int)tempf;
200 tempf = (float)tempf_int;
202 outValue = "" + tempf;
203 outValue = outValue.replace('.', ',');
206 case java.sql.Types.DOUBLE:
207 double tempd = rs.getDouble(valueIndex);
211 int tempd_int = (int)tempd;
212 tempd = (double)tempd_int;
214 outValue = "" + tempd;
215 outValue = outValue.replace('.', ',');
218 case java.sql.Types.CHAR:case java.sql.Types.VARCHAR:case java.sql.Types.LONGVARCHAR:
219 outValue = rs.getString(valueIndex);
220 if (outValue != null)
221 outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
223 case java.sql.Types.LONGVARBINARY:
224 outValue = rs.getString(valueIndex);
225 if (outValue != null)
226 outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
228 case java.sql.Types.TIMESTAMP:
229 Timestamp timestamp = (rs.getTimestamp(valueIndex));
231 outValue = timestamp.toString();
235 outValue = "<unsupported value>";
236 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
239 } catch (SQLException e) {
240 throw new StorageObjectException("Could not get Value out of Resultset -- "
248 * select-Operator um einen Datensatz zu bekommen.
249 * @param id Primaerschluessel des Datensatzes.
250 * @return liefert EntityObject des gefundenen Datensatzes oder null.
252 public Entity selectById(String id)
253 throws StorageObjectException {
255 if (id==null||id.equals(""))
256 throw new StorageObjectException("id war null");
257 if (cache != null && cache.containsKey(id))
258 return (Entity)cache.get(id); // wenn cache gesetzt, evtl. kein roundtrip zur Datenbank
260 Statement stmt=null;Connection con=getPooledCon();
261 Entity returnEntity=null;
264 String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
265 stmt = con.createStatement();
266 rs = executeSql(stmt, selectSql);
268 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
270 returnEntity = makeEntityFromResultSet(rs);
271 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
274 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
276 } catch (SQLException sqe){
277 throwSQLException(sqe,"selectById"); return null;
278 } catch (NumberFormatException e) {
279 theLog.printError("ID ist keine Zahl: " + id);
281 freeConnection(con,stmt);
288 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
289 * @param key Datenbankfeld der Bedingung.
290 * @param value Wert die der key anehmen muss.
291 * @return EntityList mit den gematchten Entities
294 public EntityList selectByFieldValue(String aField, String aValue)
295 throws StorageObjectException {
297 return selectByFieldValue(aField, aValue, 0);
301 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
302 * @param key Datenbankfeld der Bedingung.
303 * @param value Wert die der key anehmen muss.
304 * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
305 * @return EntityList mit den gematchten Entities
308 public EntityList selectByFieldValue(String aField, String aValue, int offset)
309 throws StorageObjectException {
311 return selectByWhereClause(aField + "=" + aValue, offset);
316 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
317 * Also offset wird der erste Datensatz genommen.
319 * @param wc where-Clause
320 * @return EntityList mit den gematchten Entities
321 * @exception StorageObjectException
323 public EntityList selectByWhereClause(String where)
324 throws StorageObjectException {
326 return selectByWhereClause(where, 0);
331 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
332 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
334 * @param wc where-Clause
335 * @param offset ab welchem Datensatz.
336 * @return EntityList mit den gematchten Entities
337 * @exception StorageObjectException
339 public EntityList selectByWhereClause(String whereClause, int offset)
340 throws StorageObjectException {
342 return selectByWhereClause(whereClause, null, offset);
346 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
347 * Also offset wird der erste Datensatz genommen.
348 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
350 * @param wc where-Clause
351 * @param ob orderBy-Clause
352 * @return EntityList mit den gematchten Entities
353 * @exception StorageObjectException
356 public EntityList selectByWhereClause(String where, String order)
357 throws StorageObjectException {
359 return selectByWhereClause(where, order, 0);
362 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
363 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
365 * @param wc where-Clause
366 * @param ob orderBy-Clause
367 * @param offset ab welchem Datensatz
368 * @return EntityList mit den gematchten Entities
369 * @exception StorageObjectException
372 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
373 throws StorageObjectException {
375 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
380 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
381 * @param wc where-Clause
382 * @param ob orderBy-Clause
383 * @param offset ab welchem Datensatz
384 * @param limit wieviele Datensätze
385 * @return EntityList mit den gematchten Entities
386 * @exception StorageObjectException
389 public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
390 throws StorageObjectException {
393 EntityList theReturnList=null;
401 // build sql-statement
402 if (wc != null && wc.length() == 0) {
405 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
406 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
408 selectSql.append(" where ").append(wc);
409 countSql.append(" where ").append(wc);
411 if (ob != null && !(ob.length() == 0)) {
412 selectSql.append(" order by ").append(ob);
414 if (theAdaptor.hasLimit()) {
415 if (limit > -1 && offset > -1) {
416 selectSql.append(" limit ");
417 if (theAdaptor.reverseLimit()) {
418 selectSql.append(limit).append(",").append(offset);
421 selectSql.append(offset).append(",").append(limit);
428 con = getPooledCon();
429 stmt = con.createStatement();
431 if (theAdaptor.hasLimit()) {
432 rs = executeSql(stmt, countSql.toString());
435 count = rs.getInt(1);
439 theLog.printError("Mh. Konnte nicht zaehlen: " + countSql);
442 rs = executeSql(stmt, selectSql.toString());
444 theReturnList = new EntityList();
445 if (evaluatedMetaData == false) {
446 evalMetaData(rs.getMetaData());
448 Entity theResultEntity;
450 theResultEntity = makeEntityFromResultSet(rs);
451 theReturnList.add(theResultEntity);
457 if (!(theAdaptor.hasLimit()))
459 if (theReturnList != null) {
460 theReturnList.setCount(count);
461 theReturnList.setOffset(offset);
462 theReturnList.setWhere(wc);
463 theReturnList.setOrder(ob);
464 if (offset >= limit) {
465 theReturnList.setPrevBatch(offset - limit);
467 if (offset + offsetCount < count) {
468 theReturnList.setNextBatch(offset + limit);
471 } catch (SQLException sqe) {
472 throwSQLException(sqe, "selectByWhereClause");
474 freeConnection(con, stmt);
476 return theReturnList;
480 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
482 * @param rs Das ResultSetObjekt.
483 * @return Entity Die Entity.
486 public Entity makeEntityFromResultSet (ResultSet rs) throws StorageObjectException {
487 HashMap theResultHash = new HashMap();
488 String theResult = null;
490 Entity returnEntity = null;
492 int size = metadataFields.size();
493 for (int i = 0; i < size; i++) {
494 // alle durchlaufen bis nix mehr da
495 theType = metadataTypes[i];
496 if (theType == java.sql.Types.LONGVARBINARY) {
497 InputStream us = rs.getAsciiStream(i + 1);
499 InputStreamReader is = new InputStreamReader(us);
500 char[] data = new char[32768];
501 StringBuffer theResultString = new StringBuffer();
503 while ((len = is.read(data)) > 0) {
504 theResultString.append(data, 0, len);
507 theResult = theResultString.toString();
514 theResult = getValueAsString(rs, (i + 1), theType);
516 if (theResult != null) {
517 theResultHash.put(metadataFields.get(i), theResult);
520 if (cache != null && theResultHash.containsKey(thePKeyName) && cache.containsKey((String)theResultHash.get(thePKeyName))) {
521 //theLog.printDebugInfo("CACHE: (out) "+ theResultHash.get(thePKeyName)+ " :"+theTable);
522 returnEntity = (Entity)cache.get((String)theResultHash.get(thePKeyName));
525 if (theEntityClass != null) {
526 returnEntity = (Entity)theEntityClass.newInstance();
527 returnEntity.setValues(theResultHash);
528 returnEntity.setStorage(myselfDatabase);
530 //theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
531 cache.put(returnEntity.getId(), returnEntity);
535 throwStorageObjectException("Interner Fehler theEntityClass nicht gesetzt!");
539 catch (IllegalAccessException e) {
540 throwStorageObjectException("Kein Zugriff! -- " + e.toString());
541 } catch (IOException e) {
542 throwStorageObjectException("IOException! -- " + e.toString());
543 } catch (InstantiationException e) {
544 throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
545 } catch (SQLException sqe) {
546 throwSQLException(sqe, "makeEntityFromResultSet");
553 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
554 * wird automatisch mit dem aktuellen Datum gefuellt.
557 * @return der Wert des Primary-keys der eingefügten Entity
559 public String insert (Entity theEntity) throws StorageObjectException {
560 String returnId = null;
561 Connection con = null;
562 PreparedStatement pstmt = null;
564 invalidatePopupCache();
566 ArrayList streamedInput = theEntity.streamedInput();
567 StringBuffer f = new StringBuffer();
568 StringBuffer v = new StringBuffer();
569 String aField, aValue;
570 boolean firstField = true;
572 for (int i = 0; i < getFields().size(); i++) {
573 aField = (String)getFields().get(i);
574 if (!aField.equals(thePKeyName)) {
577 if (aField.equals("webdb_create")) {
581 if (streamedInput != null && streamedInput.contains(aField)) {
585 if (theEntity.hasValueForField(aField)) {
586 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
591 // wenn Wert gegeben, dann einbauen
592 if (aValue != null) {
593 if (firstField == false) {
606 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
607 String sql = sqlBuf.toString();
608 theLog.printInfo("INSERT: " + sql);
609 con = getPooledCon();
610 con.setAutoCommit(false);
611 pstmt = con.prepareStatement(sql);
612 if (streamedInput != null) {
613 for (int i = 0; i < streamedInput.size(); i++) {
614 String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
615 pstmt.setBytes(i + 1, inputString.getBytes());
618 int ret = pstmt.executeUpdate();
623 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
624 ResultSet rs = pstmt.executeQuery();
626 returnId = rs.getString(1);
627 theEntity.setId(returnId);
628 } catch (SQLException sqe) {
629 throwSQLException(sqe, "insert");
632 con.setAutoCommit(true);
633 } catch (Exception e) {
636 freeConnection(con, pstmt);
642 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
643 * wird automatisch mit dem aktuellen Datum gefuellt.
647 public void update (Entity theEntity) throws StorageObjectException {
648 Connection con = null;
649 PreparedStatement pstmt = null;
650 ArrayList streamedInput = theEntity.streamedInput();
651 String id = theEntity.getId();
653 StringBuffer fv = new StringBuffer();
654 boolean firstField = true;
656 invalidatePopupCache();
657 // build sql statement
658 for (int i = 0; i < getFields().size(); i++) {
659 aField = (String)metadataFields.get(i);
661 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
662 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
663 if (theEntity.hasValueForField(aField)) {
664 if (firstField == false) {
670 fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
674 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
676 if (metadataFields.contains("webdb_lastchange")) {
677 sql.append(",webdb_lastchange=NOW()");
679 if (streamedInput != null) {
680 for (int i = 0; i < streamedInput.size(); i++) {
681 sql.append(",").append(streamedInput.get(i)).append("=?");
684 sql.append(" where id=").append(id);
685 theLog.printInfo("UPDATE: " + sql);
688 con = getPooledCon();
689 con.setAutoCommit(false);
690 pstmt = con.prepareStatement(sql.toString());
691 if (streamedInput != null) {
692 for (int i = 0; i < streamedInput.size(); i++) {
693 String inputString = theEntity.getValue((String)streamedInput.get(i));
694 pstmt.setBytes(i + 1, inputString.getBytes());
697 pstmt.executeUpdate();
698 } catch (SQLException sqe) {
699 throwSQLException(sqe, "update");
702 con.setAutoCommit(true);
703 } catch (Exception e) {
706 freeConnection(con, pstmt);
712 * @param id des zu loeschenden Datensatzes
713 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
715 public boolean delete (String id) throws StorageObjectException {
716 Statement stmt = null;
717 Connection con = null;
720 // loeschen des caches
721 invalidatePopupCache();
722 sql = "delete from " + theTable + " where " + thePKeyName + "='" + id +
724 theLog.printInfo("DELETE " + sql);
726 con = getPooledCon();
727 stmt = con.createStatement();
728 res = stmt.executeUpdate(sql);
729 } catch (SQLException sqe) {
730 throwSQLException(sqe, "delete");
732 freeConnection(con, stmt);
735 theLog.printInfo("CACHE: deleted " + id);
738 return (res > 0) ? true : false;
741 /* noch nicht implementiert.
742 * @return immer false
744 public boolean delete (EntityList theEntityList) {
745 invalidatePopupCache();
750 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
751 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
754 public SimpleList getPopupData () throws StorageObjectException {
759 * Holt Daten fuer Popups.
760 * @param name Name des Feldes.
761 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
762 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
764 public SimpleList getPopupData (String name, boolean hasNullValue)
765 throws StorageObjectException {
766 return getPopupData(name, hasNullValue, null);
770 * Holt Daten fuer Popups.
771 * @param name Name des Feldes.
772 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
773 * @param where Schraenkt die Selektion der Datensaetze ein.
774 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
776 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
777 return getPopupData(name, hasNullValue, where, null);
781 * Holt Daten fuer Popups.
782 * @param name Name des Feldes.
783 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
784 * @param where Schraenkt die Selektion der Datensaetze ein.
785 * @param order Gibt ein Feld als Sortierkriterium an.
786 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
788 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
790 if (hasPopupCache && popupCache != null)
792 SimpleList simpleList = null;
793 Connection con = null;
794 Statement stmt = null;
796 StringBuffer sql = new StringBuffer("select ").append(thePKeyName).append(",").append(name).append(" from ").append(theTable);
797 if (where != null && !(where.length() == 0))
798 sql.append(" where ").append(where);
799 sql.append(" order by ");
800 if (order != null && !(order.length() == 0))
806 con = getPooledCon();
807 stmt = con.createStatement();
808 ResultSet rs = executeSql(stmt, sql.toString());
810 if (evaluatedMetaData == false)
812 simpleList = new SimpleList();
813 SimpleHash popupDict;
815 popupDict = new SimpleHash();
816 popupDict.put("key", "");
817 popupDict.put("value", "--");
818 simpleList.add(popupDict);
821 popupDict = new SimpleHash();
822 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
823 popupDict.put("value", rs.getString(2));
824 simpleList.add(popupDict);
828 } catch (Exception e) {
829 theLog.printDebugInfo(e.toString());
830 throw new StorageObjectException(e.toString());
832 freeConnection(con, stmt);
835 popupCache = simpleList;
841 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
842 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
843 * Tabellen Verwendung finden.
844 * @return SimpleHash mit den Tabellezeilen.
846 public SimpleHash getHashData () {
847 if (hashCache == null) {
849 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
851 } catch (StorageObjectException e) {
852 theLog.printDebugInfo(e.toString());
858 /* invalidates the popupCache
860 protected void invalidatePopupCache () {
862 /** @todo invalidates toooo much */
868 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
869 * @param stmt Statemnt
870 * @param sql Sql-String
872 * @exception StorageObjectException
874 public ResultSet executeSql (Statement stmt, String sql)
875 throws StorageObjectException, SQLException
878 long startTime = (new java.util.Date()).getTime();
880 rs = stmt.executeQuery(sql);
881 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
884 catch (SQLException e)
886 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
895 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
896 * getimed und geloggt.
897 * @param stmt PreparedStatement mit der SQL-Anweisung
898 * @return Liefert ResultSet des Statements zurueck.
899 * @exception StorageObjectException, SQLException
901 public ResultSet executeSql (PreparedStatement stmt) throws StorageObjectException,
904 long startTime = (new java.util.Date()).getTime();
905 ResultSet rs = stmt.executeQuery();
906 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
911 * returns the number of rows in the table
913 public int getSize(String where)
914 throws SQLException,StorageObjectException
916 long startTime = (new java.util.Date()).getTime();
917 String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
918 //theLog.printDebugInfo("trying: "+ sql);
919 Connection con = null;
920 Statement stmt = null;
924 con = getPooledCon();
925 stmt = con.createStatement();
926 ResultSet rs = executeSql(stmt,sql);
928 result = rs.getInt(1);
930 } catch (SQLException e) {
931 theLog.printError(e.toString());
933 freeConnection(con,stmt);
935 theLog.printInfo(theTable + " has "+ result +" rows where " + where);
936 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
940 public int executeUpdate(Statement stmt, String sql)
941 throws StorageObjectException, SQLException
944 long startTime = (new java.util.Date()).getTime();
947 rs = stmt.executeUpdate(sql);
948 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
950 catch (SQLException e)
952 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
959 public int executeUpdate(String sql)
960 throws StorageObjectException, SQLException
963 long startTime = (new java.util.Date()).getTime();
964 Connection con=null;PreparedStatement pstmt=null;
967 pstmt = con.prepareStatement(sql);
968 result = pstmt.executeUpdate();
970 catch (Exception e) {
971 theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
972 throw new StorageObjectException("executeUpdate failed: "+e.toString());
974 finally { freeConnection(con,pstmt); }
975 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
980 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
981 * @param md ResultSetMetaData
982 * @exception StorageObjectException
984 private void evalMetaData (ResultSetMetaData md) throws StorageObjectException {
985 this.evaluatedMetaData = true;
986 this.metadataFields = new ArrayList();
987 this.metadataLabels = new ArrayList();
988 this.metadataNotNullFields = new ArrayList();
990 int numFields = md.getColumnCount();
991 this.metadataTypes = new int[numFields];
994 for (int i = 1; i <= numFields; i++) {
995 aField = md.getColumnName(i);
996 metadataFields.add(aField);
997 metadataLabels.add(md.getColumnLabel(i));
998 aType = md.getColumnType(i);
999 metadataTypes[i - 1] = aType;
1000 if (aField.equals(thePKeyName)) {
1001 thePKeyType = aType;
1003 if (md.isNullable(i) == md.columnNullable) {
1004 metadataNotNullFields.add(aField);
1007 } catch (SQLException e) {
1008 throwSQLException(e, "evalMetaData");
1013 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1014 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1016 private void get_meta_data () throws StorageObjectException {
1017 Connection con = null;
1018 PreparedStatement pstmt = null;
1019 String sql = "select * from " + theTable + " where 0=1";
1021 con = getPooledCon();
1022 pstmt = con.prepareStatement(sql);
1023 theLog.printInfo("METADATA: " + sql);
1024 ResultSet rs = pstmt.executeQuery();
1025 evalMetaData(rs.getMetaData());
1027 } catch (SQLException e) {
1028 throwSQLException(e, "get_meta_data");
1030 freeConnection(con, pstmt);
1035 * Datenbankverbindung wird geschlossen
1037 public void disconnectPool () throws StorageObjectException {
1039 myBroker.destroy(100);
1040 } catch (SQLException sqe) {
1041 throwSQLException(sqe, "disconnectPool");
1046 * Returns Connection-Object out of the PoolBroker.
1048 * @return Connection Object.
1050 public Connection getPooledCon () throws StorageObjectException {
1051 if (myBroker != null) {
1052 Connection con = myBroker.getConnection();
1056 throw new StorageObjectException("No connection to database!");
1060 * Connection und StatementObjekt werden geschlossen und an den Connectionpool
1062 * @param con Connection zur Datenbank
1063 * @param stmt Statement-Objekt
1065 public void freeConnection (Connection con, Statement stmt)
1066 throws StorageObjectException {
1070 } catch (SQLException e1) {
1071 theLog.printDebugInfo(e1.toString());
1072 throw new StorageObjectException("DB, in freeConnection: "+e1.toString());
1075 myBroker.freeConnection(con);
1077 theLog.printDebugInfo("Con was null!");
1078 throw new StorageObjectException("Con was null!");
1083 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1084 * @param sqe SQLException
1085 * @param wo Funktonsname, in der die SQLException geworfen wurde
1086 * @exception StorageObjectException
1088 protected void throwSQLException (SQLException sqe, String wo) throws StorageObjectException {
1090 String message = "";
1093 state = sqe.getSQLState();
1094 message = sqe.getMessage();
1095 vendor = sqe.getErrorCode();
1097 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1099 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1103 protected void _throwStorageObjectException (Exception e, String wo) throws StorageObjectException {
1105 theLog.printError(e.toString()+ wo);
1106 throw new StorageObjectException(wo + e.toString());
1108 theLog.printError(wo);
1109 throw new StorageObjectException(wo);
1115 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach eine StorageObjectException
1116 * @param message Nachricht mit dem Fehler
1117 * @exception StorageObjectException
1119 void throwStorageObjectException (String message) throws StorageObjectException {
1120 _throwStorageObjectException(null, message);