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;
52 * Kontruktor bekommt den Filenamen des Konfigurationsfiles übergeben.
53 * Aus diesem file werden <code>Database.Logfile</code>,
54 * <code>Database.Username</code>,<code>Database.Password</code>,
55 * <code>Database.Host</code> und <code>Database.Adaptor</code>
56 * ausgelesen und ein Broker für die Verbindugen zur Datenbank
59 * @param String confFilename Dateiname der Konfigurationsdatei
61 public Database() throws StorageObjectException {
62 theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("Database.Logfile"));
63 String database_username=MirConfig.getProp("Database.Username");
64 String database_password=MirConfig.getProp("Database.Password");
65 String database_host=MirConfig.getProp("Database.Host");
66 String theAdaptorName=MirConfig.getProp("Database.Adaptor");
68 theEntityClass = Class.forName("mir.entity.GenericEntity");
69 theAdaptor = (DatabaseAdaptor)Class.forName(theAdaptorName).newInstance();
70 defaultLimit = Integer.parseInt(MirConfig.getProp("Database.Limit"));
71 database_driver=theAdaptor.getDriver();
72 database_url=theAdaptor.getURL(database_username,database_password,database_host);
73 theLog.printDebugInfo("adding Broker with: " +database_driver+":"+database_url );
74 MirConfig.addBroker(database_driver,database_url);
75 myBroker=MirConfig.getBroker();
78 theLog.printError("Bei Konstruktion von Database() with " + theAdaptorName + " -- " +e.toString());
79 throw new StorageObjectException(e.toString());
84 * Liefert die Entity-Klasse zurück, in der eine Datenbankzeile gewrappt
85 * wird. Wird die Entity-Klasse durch die erbende Klasse nicht überschrieben,
86 * wird eine mir.entity.GenericEntity erzeugt.
88 * @return Class-Objekt der Entity
90 public java.lang.Class getEntityClass () {
91 return theEntityClass;
95 * Liefert die Standardbeschränkung von select-Statements zurück, also
96 * wieviel Datensätze per Default selektiert werden.
98 * @return Standard-Anzahl der Datensätze
100 public int getLimit () {
105 * Liefert den Namen des Primary-Keys zurück. Wird die Variable nicht von
106 * der erbenden Klasse überschrieben, so ist der Wert <code>PKEY</code>
107 * @return Name des Primary-Keys
109 public String getIdName () {
114 * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
116 * @return Name der Tabelle
118 public String getTableName () {
123 * Dient dazu vererbte Tabellen bei objectrelationalen DBMS
124 * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet wird.
125 * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
129 public String getCoreTable(){
130 if (theCoreTable!=null) return theCoreTable;
131 else return theTable;
135 * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
136 * @return int-Array mit den Typen der Felder
137 * @exception StorageObjectException
139 public int[] getTypes () throws StorageObjectException {
140 if (metadataTypes == null)
142 return metadataTypes;
146 * Liefert eine Liste der Labels der Tabellenfelder
147 * @return ArrayListe mit Labeln
148 * @exception StorageObjectException
150 public ArrayList getLabels () throws StorageObjectException {
151 if (metadataLabels == null)
153 return metadataLabels;
157 * Liefert eine Liste der Felder der Tabelle
158 * @return ArrayList mit Feldern
159 * @exception StorageObjectException
161 public ArrayList getFields () throws StorageObjectException {
162 if (metadataFields == null)
164 return metadataFields;
169 * Gets value out of ResultSet according to type and converts to String
170 * @param inValue Wert aus ResultSet.
171 * @param aType Datenbanktyp.
172 * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
173 * dann /unsupported value/
175 private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
176 String outValue = null;
180 case java.sql.Types.BIT:
181 outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
183 case java.sql.Types.INTEGER:case java.sql.Types.SMALLINT:case java.sql.Types.TINYINT:case java.sql.Types.BIGINT:
184 int out = rs.getInt(valueIndex);
186 outValue = new Integer(out).toString();
188 case java.sql.Types.NUMERIC:
189 long outl = rs.getLong(valueIndex);
191 outValue = new Long(outl).toString();
193 case java.sql.Types.REAL:
194 float tempf = rs.getFloat(valueIndex);
198 int tempf_int = (int)tempf;
199 tempf = (float)tempf_int;
201 outValue = "" + tempf;
202 outValue = outValue.replace('.', ',');
205 case java.sql.Types.DOUBLE:
206 double tempd = rs.getDouble(valueIndex);
210 int tempd_int = (int)tempd;
211 tempd = (double)tempd_int;
213 outValue = "" + tempd;
214 outValue = outValue.replace('.', ',');
217 case java.sql.Types.CHAR:case java.sql.Types.VARCHAR:case java.sql.Types.LONGVARCHAR:
218 outValue = rs.getString(valueIndex);
219 if (outValue != null)
220 outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
222 case java.sql.Types.LONGVARBINARY:
223 outValue = rs.getString(valueIndex);
224 if (outValue != null)
225 outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
227 case java.sql.Types.TIMESTAMP:
228 Timestamp timestamp = (rs.getTimestamp(valueIndex));
230 outValue = timestamp.toString();
234 outValue = "<unsupported value>";
235 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
238 } catch (SQLException e) {
239 throw new StorageObjectException("Could not get Value out of Resultset -- "
247 * select-Operator um einen Datensatz zu bekommen.
248 * @param id Primaerschluessel des Datensatzes.
249 * @return liefert EntityObject des gefundenen Datensatzes oder null.
251 public Entity selectById(String id)
252 throws StorageObjectException {
254 if (id==null||id.equals(""))
255 throw new StorageObjectException("id war null");
256 if (cache != null && cache.containsKey(id))
257 return (Entity)cache.get(id); // wenn cache gesetzt, evtl. kein roundtrip zur Datenbank
259 Statement stmt=null;Connection con=getPooledCon();
260 Entity returnEntity=null;
263 String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
264 stmt = con.createStatement();
265 rs = executeSql(stmt, selectSql);
267 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
269 returnEntity = makeEntityFromResultSet(rs);
270 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
273 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
275 } catch (SQLException sqe){
276 throwSQLException(sqe,"selectById"); return null;
277 } catch (NumberFormatException e) {
278 theLog.printError("ID ist keine Zahl: " + id);
280 freeConnection(con,stmt);
287 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
288 * @param key Datenbankfeld der Bedingung.
289 * @param value Wert die der key anehmen muss.
290 * @return EntityList mit den gematchten Entities
293 public EntityList selectByFieldValue(String aField, String aValue)
294 throws StorageObjectException {
296 return selectByFieldValue(aField, aValue, 0);
300 * select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
301 * @param key Datenbankfeld der Bedingung.
302 * @param value Wert die der key anehmen muss.
303 * @param offset Gibt an ab welchem Datensatz angezeigt werden soll.
304 * @return EntityList mit den gematchten Entities
307 public EntityList selectByFieldValue(String aField, String aValue, int offset)
308 throws StorageObjectException {
310 return selectByWhereClause(aField + "=" + aValue, offset);
315 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
316 * Also offset wird der erste Datensatz genommen.
318 * @param wc where-Clause
319 * @return EntityList mit den gematchten Entities
320 * @exception StorageObjectException
322 public EntityList selectByWhereClause(String where)
323 throws StorageObjectException {
325 return selectByWhereClause(where, 0);
330 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
331 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
333 * @param wc where-Clause
334 * @param offset ab welchem Datensatz.
335 * @return EntityList mit den gematchten Entities
336 * @exception StorageObjectException
338 public EntityList selectByWhereClause(String whereClause, int offset)
339 throws StorageObjectException {
341 return selectByWhereClause(whereClause, null, offset);
345 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
346 * Also offset wird der erste Datensatz genommen.
347 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
349 * @param wc where-Clause
350 * @param ob orderBy-Clause
351 * @return EntityList mit den gematchten Entities
352 * @exception StorageObjectException
355 public EntityList selectByWhereClause(String where, String order)
356 throws StorageObjectException {
358 return selectByWhereClause(where, order, 0);
361 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
362 * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
364 * @param wc where-Clause
365 * @param ob orderBy-Clause
366 * @param offset ab welchem Datensatz
367 * @return EntityList mit den gematchten Entities
368 * @exception StorageObjectException
371 public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
372 throws StorageObjectException {
374 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
379 * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
380 * @param wc where-Clause
381 * @param ob orderBy-Clause
382 * @param offset ab welchem Datensatz
383 * @param limit wieviele Datensätze
384 * @return EntityList mit den gematchten Entities
385 * @exception StorageObjectException
388 public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
389 throws StorageObjectException {
392 EntityList theReturnList=null;
400 // build sql-statement
401 if (wc != null && wc.length() == 0) {
404 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
405 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
407 selectSql.append(" where ").append(wc);
408 countSql.append(" where ").append(wc);
410 if (ob != null && !(ob.length() == 0)) {
411 selectSql.append(" order by ").append(ob);
413 if (theAdaptor.hasLimit()) {
414 if (limit > -1 && offset > -1) {
415 selectSql.append(" limit ");
416 if (theAdaptor.reverseLimit()) {
417 selectSql.append(limit).append(",").append(offset);
420 selectSql.append(offset).append(",").append(limit);
427 con = getPooledCon();
428 stmt = con.createStatement();
430 if (theAdaptor.hasLimit()) {
431 rs = executeSql(stmt, countSql.toString());
434 count = rs.getInt(1);
438 theLog.printError("Mh. Konnte nicht zaehlen: " + countSql);
441 rs = executeSql(stmt, selectSql.toString());
443 theReturnList = new EntityList();
444 if (evaluatedMetaData == false) {
445 evalMetaData(rs.getMetaData());
447 Entity theResultEntity;
449 theResultEntity = makeEntityFromResultSet(rs);
450 theReturnList.add(theResultEntity);
456 if (!(theAdaptor.hasLimit()))
458 if (theReturnList != null) {
459 theReturnList.setCount(count);
460 theReturnList.setOffset(offset);
461 theReturnList.setWhere(wc);
462 theReturnList.setOrder(ob);
463 if (offset >= limit) {
464 theReturnList.setPrevBatch(offset - limit);
466 if (offset + offsetCount < count) {
467 theReturnList.setNextBatch(offset + limit);
470 } catch (SQLException sqe) {
471 throwSQLException(sqe, "selectByWhereClause");
473 freeConnection(con, stmt);
475 return theReturnList;
479 * Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
481 * @param rs Das ResultSetObjekt.
482 * @return Entity Die Entity.
485 public Entity makeEntityFromResultSet (ResultSet rs) throws StorageObjectException {
486 HashMap theResultHash = new HashMap();
487 String theResult = null;
489 Entity returnEntity = null;
491 int size = metadataFields.size();
492 for (int i = 0; i < size; i++) {
493 // alle durchlaufen bis nix mehr da
494 theType = metadataTypes[i];
495 if (theType == java.sql.Types.LONGVARBINARY) {
496 InputStream us = rs.getAsciiStream(i + 1);
498 InputStreamReader is = new InputStreamReader(us);
499 char[] data = new char[32768];
500 StringBuffer theResultString = new StringBuffer();
502 while ((len = is.read(data)) > 0) {
503 theResultString.append(data, 0, len);
506 theResult = theResultString.toString();
513 theResult = getValueAsString(rs, (i + 1), theType);
515 if (theResult != null) {
516 theResultHash.put(metadataFields.get(i), theResult);
519 if (cache != null && theResultHash.containsKey(thePKeyName) && cache.containsKey((String)theResultHash.get(thePKeyName))) {
520 //theLog.printDebugInfo("CACHE: (out) "+ theResultHash.get(thePKeyName)+ " :"+theTable);
521 returnEntity = (Entity)cache.get((String)theResultHash.get(thePKeyName));
524 if (theEntityClass != null) {
525 returnEntity = (Entity)theEntityClass.newInstance();
526 returnEntity.setValues(theResultHash);
527 returnEntity.setStorage(myselfDatabase);
529 //theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
530 cache.put(returnEntity.getId(), returnEntity);
534 throwStorageObjectException("Interner Fehler theEntityClass nicht gesetzt!");
538 catch (IllegalAccessException e) {
539 throwStorageObjectException("Kein Zugriff! -- " + e.toString());
540 } catch (IOException e) {
541 throwStorageObjectException("IOException! -- " + e.toString());
542 } catch (InstantiationException e) {
543 throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
544 } catch (SQLException sqe) {
545 throwSQLException(sqe, "makeEntityFromResultSet");
552 * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
553 * wird automatisch mit dem aktuellen Datum gefuellt.
556 * @return der Wert des Primary-keys der eingefügten Entity
558 public String insert (Entity theEntity) throws StorageObjectException {
559 String returnId = null;
560 Connection con = null;
561 PreparedStatement pstmt = null;
563 invalidatePopupCache();
565 ArrayList streamedInput = theEntity.streamedInput();
566 StringBuffer f = new StringBuffer();
567 StringBuffer v = new StringBuffer();
568 String aField, aValue;
569 boolean firstField = true;
571 for (int i = 0; i < getFields().size(); i++) {
572 aField = (String)getFields().get(i);
573 if (!aField.equals(thePKeyName)) {
576 if (aField.equals("webdb_create")) {
580 if (streamedInput != null && streamedInput.contains(aField)) {
584 if (theEntity.hasValueForField(aField)) {
585 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
590 // wenn Wert gegeben, dann einbauen
591 if (aValue != null) {
592 if (firstField == false) {
605 StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
606 String sql = sqlBuf.toString();
607 theLog.printInfo("INSERT: " + sql);
608 con = getPooledCon();
609 con.setAutoCommit(false);
610 pstmt = con.prepareStatement(sql);
611 if (streamedInput != null) {
612 for (int i = 0; i < streamedInput.size(); i++) {
613 String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
614 pstmt.setBytes(i + 1, inputString.getBytes());
617 int ret = pstmt.executeUpdate();
622 pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
623 ResultSet rs = pstmt.executeQuery();
625 returnId = rs.getString(1);
626 theEntity.setId(returnId);
627 } catch (SQLException sqe) {
628 throwSQLException(sqe, "insert");
631 con.setAutoCommit(true);
632 } catch (Exception e) {
635 freeConnection(con, pstmt);
641 * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
642 * wird automatisch mit dem aktuellen Datum gefuellt.
646 public void update (Entity theEntity) throws StorageObjectException {
647 Connection con = null;
648 PreparedStatement pstmt = null;
649 ArrayList streamedInput = theEntity.streamedInput();
650 String id = theEntity.getId();
652 StringBuffer fv = new StringBuffer();
653 boolean firstField = true;
655 invalidatePopupCache();
656 // build sql statement
657 for (int i = 0; i < getFields().size(); i++) {
658 aField = (String)metadataFields.get(i);
660 if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
661 aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
662 if (theEntity.hasValueForField(aField)) {
663 if (firstField == false) {
669 fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
673 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
675 if (metadataFields.contains("webdb_lastchange")) {
676 sql.append(",webdb_lastchange=NOW()");
678 if (streamedInput != null) {
679 for (int i = 0; i < streamedInput.size(); i++) {
680 sql.append(",").append(streamedInput.get(i)).append("=?");
683 sql.append(" where id=").append(id);
684 theLog.printInfo("UPDATE: " + sql);
687 con = getPooledCon();
688 con.setAutoCommit(false);
689 pstmt = con.prepareStatement(sql.toString());
690 if (streamedInput != null) {
691 for (int i = 0; i < streamedInput.size(); i++) {
692 String inputString = theEntity.getValue((String)streamedInput.get(i));
693 pstmt.setBytes(i + 1, inputString.getBytes());
696 pstmt.executeUpdate();
697 } catch (SQLException sqe) {
698 throwSQLException(sqe, "update");
701 con.setAutoCommit(true);
702 } catch (Exception e) {
705 freeConnection(con, pstmt);
711 * @param id des zu loeschenden Datensatzes
712 * @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
714 public boolean delete (String id) throws StorageObjectException {
715 Statement stmt = null;
716 Connection con = null;
719 // loeschen des caches
720 invalidatePopupCache();
721 sql = "delete from " + theTable + " where " + thePKeyName + "='" + id +
723 theLog.printInfo("DELETE " + sql);
725 con = getPooledCon();
726 stmt = con.createStatement();
727 res = stmt.executeUpdate(sql);
728 } catch (SQLException sqe) {
729 throwSQLException(sqe, "delete");
731 freeConnection(con, stmt);
734 theLog.printInfo("CACHE: deleted " + id);
737 return (res > 0) ? true : false;
740 /* noch nicht implementiert.
741 * @return immer false
743 public boolean delete (EntityList theEntityList) {
744 invalidatePopupCache();
749 * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
750 * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
753 public SimpleList getPopupData () throws StorageObjectException {
758 * Holt Daten fuer Popups.
759 * @param name Name des Feldes.
760 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
761 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
763 public SimpleList getPopupData (String name, boolean hasNullValue)
764 throws StorageObjectException {
765 return getPopupData(name, hasNullValue, null);
769 * Holt Daten fuer Popups.
770 * @param name Name des Feldes.
771 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
772 * @param where Schraenkt die Selektion der Datensaetze ein.
773 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
775 public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
776 return getPopupData(name, hasNullValue, where, null);
780 * Holt Daten fuer Popups.
781 * @param name Name des Feldes.
782 * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt.
783 * @param where Schraenkt die Selektion der Datensaetze ein.
784 * @param order Gibt ein Feld als Sortierkriterium an.
785 * @return SimpleList Gibt freemarker.template.SimpleList zurueck.
787 public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
789 if (hasPopupCache && popupCache != null)
791 SimpleList simpleList = null;
792 Connection con = null;
793 Statement stmt = null;
795 StringBuffer sql = new StringBuffer("select ").append(thePKeyName).append(",").append(name).append(" from ").append(theTable);
796 if (where != null && !(where.length() == 0))
797 sql.append(" where ").append(where);
798 sql.append(" order by ");
799 if (order != null && !(order.length() == 0))
805 con = getPooledCon();
806 stmt = con.createStatement();
807 ResultSet rs = executeSql(stmt, sql.toString());
809 if (evaluatedMetaData == false)
811 simpleList = new SimpleList();
812 SimpleHash popupDict;
814 popupDict = new SimpleHash();
815 popupDict.put("key", "");
816 popupDict.put("value", "--");
817 simpleList.add(popupDict);
820 popupDict = new SimpleHash();
821 popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
822 popupDict.put("value", rs.getString(2));
823 simpleList.add(popupDict);
827 } catch (Exception e) {
828 theLog.printDebugInfo(e.toString());
829 throw new StorageObjectException(e.toString());
831 freeConnection(con, stmt);
834 popupCache = simpleList;
840 * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
841 * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
842 * Tabellen Verwendung finden.
843 * @return SimpleHash mit den Tabellezeilen.
845 public SimpleHash getHashData () {
846 if (hashCache == null) {
848 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
850 } catch (StorageObjectException e) {
851 theLog.printDebugInfo(e.toString());
857 /* invalidates the popupCache
859 protected void invalidatePopupCache () {
861 /** @todo invalidates toooo much */
867 * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
868 * @param stmt Statemnt
869 * @param sql Sql-String
871 * @exception StorageObjectException
873 public ResultSet executeSql (Statement stmt, String sql)
874 throws StorageObjectException, SQLException
877 long startTime = (new java.util.Date()).getTime();
879 rs = stmt.executeQuery(sql);
880 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
883 catch (SQLException e)
885 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
894 * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
895 * getimed und geloggt.
896 * @param stmt PreparedStatement mit der SQL-Anweisung
897 * @return Liefert ResultSet des Statements zurueck.
898 * @exception StorageObjectException, SQLException
900 public ResultSet executeSql (PreparedStatement stmt) throws StorageObjectException,
903 long startTime = (new java.util.Date()).getTime();
904 ResultSet rs = stmt.executeQuery();
905 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
910 * returns the number of rows in the table
912 public int getSize(String where)
913 throws SQLException,StorageObjectException
915 long startTime = (new java.util.Date()).getTime();
916 String sql = "SELECT count(*) FROM "+ theTable + " where " + where;
917 //theLog.printDebugInfo("trying: "+ sql);
918 Connection con = null;
919 Statement stmt = null;
923 con = getPooledCon();
924 stmt = con.createStatement();
925 ResultSet rs = executeSql(stmt,sql);
927 result = rs.getInt(1);
929 } catch (SQLException e) {
930 theLog.printError(e.toString());
932 freeConnection(con,stmt);
934 theLog.printInfo(theTable + " has "+ result +" rows where " + where);
935 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
939 public int executeUpdate(Statement stmt, String sql)
940 throws StorageObjectException, SQLException
943 long startTime = (new java.util.Date()).getTime();
946 rs = stmt.executeUpdate(sql);
947 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
949 catch (SQLException e)
951 theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime() - startTime) + "ms. for: "
958 public int executeUpdate(String sql)
959 throws StorageObjectException, SQLException
962 long startTime = (new java.util.Date()).getTime();
963 Connection con=null;PreparedStatement pstmt=null;
966 pstmt = con.prepareStatement(sql);
967 result = pstmt.executeUpdate();
969 catch (Exception e) {
970 theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
971 throw new StorageObjectException("executeUpdate failed: "+e.toString());
973 finally { freeConnection(con,pstmt); }
974 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: " + sql);
979 * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
980 * @param md ResultSetMetaData
981 * @exception StorageObjectException
983 private void evalMetaData (ResultSetMetaData md) throws StorageObjectException {
984 this.evaluatedMetaData = true;
985 this.metadataFields = new ArrayList();
986 this.metadataLabels = new ArrayList();
987 this.metadataNotNullFields = new ArrayList();
989 int numFields = md.getColumnCount();
990 this.metadataTypes = new int[numFields];
993 for (int i = 1; i <= numFields; i++) {
994 aField = md.getColumnName(i);
995 metadataFields.add(aField);
996 metadataLabels.add(md.getColumnLabel(i));
997 aType = md.getColumnType(i);
998 metadataTypes[i - 1] = aType;
999 if (aField.equals(thePKeyName)) {
1000 thePKeyType = aType;
1002 if (md.isNullable(i) == md.columnNullable) {
1003 metadataNotNullFields.add(aField);
1006 } catch (SQLException e) {
1007 throwSQLException(e, "evalMetaData");
1012 * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1013 * um die alle Columns und Typen einer Tabelle zu ermitteln.
1015 private void get_meta_data () throws StorageObjectException {
1016 Connection con = null;
1017 PreparedStatement pstmt = null;
1018 String sql = "select * from " + theTable + " where 0=1";
1020 con = getPooledCon();
1021 pstmt = con.prepareStatement(sql);
1022 theLog.printInfo("METADATA: " + sql);
1023 ResultSet rs = pstmt.executeQuery();
1024 evalMetaData(rs.getMetaData());
1026 } catch (SQLException e) {
1027 throwSQLException(e, "get_meta_data");
1029 freeConnection(con, pstmt);
1034 * Datenbankverbindung wird geschlossen
1036 public void disconnectPool () throws StorageObjectException {
1038 myBroker.destroy(100);
1039 } catch (SQLException sqe) {
1040 throwSQLException(sqe, "disconnectPool");
1045 * Returns Connection-Object out of the PoolBroker.
1047 * @return Connection Object.
1049 public Connection getPooledCon () throws StorageObjectException {
1050 if (myBroker != null) {
1051 Connection con = myBroker.getConnection();
1055 throw new StorageObjectException("No connection to database!");
1059 * Connection und StatementObjekt werden geschlossen und an den Connectionpool
1061 * @param con Connection zur Datenbank
1062 * @param stmt Statement-Objekt
1064 public void freeConnection (Connection con, Statement stmt)
1065 throws StorageObjectException {
1069 } catch (SQLException e1) {
1070 theLog.printDebugInfo(e1.toString());
1071 throw new StorageObjectException("DB, in freeConnection: "+e1.toString());
1074 myBroker.freeConnection(con);
1076 theLog.printDebugInfo("Con was null!");
1077 throw new StorageObjectException("Con was null!");
1082 * Wertet SQLException aus und wirft dannach eine StorageObjectException
1083 * @param sqe SQLException
1084 * @param wo Funktonsname, in der die SQLException geworfen wurde
1085 * @exception StorageObjectException
1087 protected void throwSQLException (SQLException sqe, String wo) throws StorageObjectException {
1089 String message = "";
1092 state = sqe.getSQLState();
1093 message = sqe.getMessage();
1094 vendor = sqe.getErrorCode();
1096 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1098 throw new StorageObjectException((sqe == null) ? "undefined sql exception" :
1102 protected void _throwStorageObjectException (Exception e, String wo) throws StorageObjectException {
1104 theLog.printError(e.toString()+ wo);
1105 throw new StorageObjectException(wo + e.toString());
1107 theLog.printError(wo);
1108 throw new StorageObjectException(wo);
1114 * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach eine StorageObjectException
1115 * @param message Nachricht mit dem Fehler
1116 * @exception StorageObjectException
1118 void throwStorageObjectException (String message) throws StorageObjectException {
1119 _throwStorageObjectException(null, message);