ulrich
2015-05-05 964f7da7f5a63b7ca5477bd27e26e73aa16daa92
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
/*
 *  BaseLink - Generic object relational mapping
 *  Copyright (C) 2011  Ulrich Hilger, http://uhilger.de
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/
 */
package de.uhilger.baselink;
 
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
 
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
 
/**
 * Class <code>PersistenceManager</code> stores and retrieves Java objects to and from a 
 * relational database. Any object that implements interface <code>Record</code> can be 
 * read from or written to a database using this class.
 * 
 * <p>In addition, any other class can be used directly as PersistenceManager 
 * wraps such other objects into <code>GenericRecord</code> objects implicitly.</p>
 * 
 * <p>Major aim of class <code>PersistenceManager</code> is to encapsulate the management 
 * of database related objects such as <code>Connection</code>, <code>Statement</code> and 
 * <code>ResultSet</code> to make sure proper opening and closing especially when used in 
 * conjunction with a connection pool.</p>
 * 
 * <p>In addition <code>PersistenceManager</code> provides methods that allow for an 
 * abundance of database read/write operations for convenience providing a base 
 * class to extend for individual needs.</p> 
 * 
 * @author Copyright (c) Ulrich Hilger, <a href="http://uhilger.de">http://uhilger.de</a>
 * @author Published under the terms and conditions of
 * the <a href="http://www.gnu.org/licenses/" target="_blank">GNU General Public License</a>
 * @version 3, March 22, 2011
 */
public class PersistenceManager {
  
  private static final Logger logger = Logger.getLogger(PersistenceManager.class.getName());
 
  public static final String NULL_STR = "null";
  /** reference to data source to use for connections in production mode */
  protected DataSource ds;
  /** reference to JDBC url to use for connections in development mode */
  protected String dburl;
 
  /**
   * Create a new object of class PersistenceManager
   */
  public PersistenceManager() {
    super();
  }
 
  /**
   * Set the JDBC driver class name
   * @param driverName  name of JDBC driver class name
   * @throws ClassNotFoundException  when driver is not found
   */
  public void setDriverName(String driverName) throws ClassNotFoundException {
    Class.forName(driverName);
  }
 
  /**
   * Set the database
   *
   * <p>Use either this method together with method setDriverName or
   * method setDataSourceName to indicate the connection type</p>
   *
   * @param url  JDBC url
   */
  public void setDatabase(String url) {
    this.dburl = url;
  }
 
  /**
   * Set the database
   *
   * <p>Use either this method or method setDataSourceName to indicate the connection type</p>
   *
   * @param driverName class name of JDBC driver
   * @param url JDBC url
   * @throws ClassNotFoundException  when driver is not found
   */
  public void setDatabase(String driverName, String url) throws ClassNotFoundException {
    Class.forName(driverName);
    this.dburl = url;
  }
 
  /**
   * Set name of DataSource
   *
   * <p>Use either this method or method setDatabase to indicate the connection type</p>
   *
   * @param dataSourceName  name of DataSource
   * @throws NamingException  when JNDI lookup fails
   */
  public void setDataSourceName(String dataSourceName) throws NamingException {
    Context initCtx = new InitialContext();
    Context envCtx = (Context) initCtx.lookup("java:comp/env");
    ds = (DataSource) envCtx.lookup(dataSourceName);
  }
 
  /**
   * Get a database connection
   * @return  a database connection
   * @throws SQLException
   */
  public Connection getConnection() {
    Connection c = null;
    try {
      if (dburl != null) {
        c = DriverManager.getConnection(dburl);
      } else if(ds != null) {
        c = ds.getConnection();
      } else {
        //throw new SQLException("Unable to get connection, DataSource and database URL are null.");
      }
    } catch(Exception ex) {
      ex.printStackTrace();
    }
    return c;
  }
  
  /* -------------------- deletes ---------------------------- */
 
  /**
   * Delete a given object from the database
   *
   * <p>Use this method for single deletes. In cases where
   * several subsequent deletes for objects of the same class
   * are required the use of method <code>delete(Object, Record)</code>
   * is recommended instead to minimise instantiation
   * overhead.</p>
   *
   * @param o object to delete
   * @return  the deleted object
   */
  public Object delete(Object o) {
    return delete(o, new GenericRecord(o.getClass()));
  }
 
  /**
   * Delete a given object from the database
   *
   * <p>Use this method for single deletes. In cases where
   * several subsequent deletes for objects of the same class
   * are required the use of method <code>delete(Connection, Object, Record)</code>
   * is recommended instead to minimise instantiation
   * overhead.</p>
   *
   * @param c  the connection to use, expected to be open and established
   * @param o  object to delete
   * @return  the deleted object
   */
  public Object delete(Connection c, Object o) {
    return delete(c, o, new GenericRecord(o.getClass()));
  }
 
  /**
   * Delete a given object from the database
   * @param o object to delete
   * @param record  reference to object to use to map between object and database
   * @return  the deleted object
   */
  public Object delete(Object o, Record record) {
    Connection c = null;
    try {
      c = getConnection();
      o = delete(c, o, record);
      c.close();
      c = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeConnectionFinally(c);
    }
    return o;
  }
 
  /**
   * Delete a given object from the database
   * @param c  the connection to use, expected to be open and established
   * @param o  object to delete
   * @param record reference to object to use to map between object and database
   * @return the deleted object
   */
  public Object delete(Connection c, Object o, Record record) {
    Object deletedObject = null;
    PreparedStatement ps = null;
    try {
      ps = record.getDeleteStatment(c, o);
      ps.executeUpdate();
      ps.close();
      ps = null;
      deletedObject = o;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeStatementFinally(ps);
    }
    return deletedObject;
  }
  
  /* ---------------------- inserts -------------------- */
 
  /**
   * Add an object to the database
   *
   * <p>Use this method for single inserts. In cases where
   * several subsequent inserts for objects of the same class
   * are required the use of method <code>insert(Object, Record)</code>
   * is recommended instead to minimise instantiation
   * overhead.</p>
   *
   * @param o  the object to add
   * @return  the added object
   */
  public Object insert(Object o) {
    return insert(o, new GenericRecord(o.getClass()));
  }
 
  /**
   * Add an object to the database
   *
   * <p>Use this method for single inserts. In cases where
   * several subsequent inserts for objects of the same class
   * are required the use of method <code>insert(Connection, Object, Record)</code>
   * is recommended instead to minimise instantiation
   * overhead.</p>
   *
   * @param c  the connection to use, expected to be open and established
   * @param o  the object to add
   * @return  the object added to the database
   */
  public Object insert(Connection c, Object o) {
    return insert(c, o, new GenericRecord(o.getClass()));
  }
 
  /**
   * Add an object to the database
   * @param o object to add
   * @param record  reference to object to use to map between object and database
   * @return  the added object
   */
  public Object insert(Object o, Record record) {
    Connection c = null;
    try {
      c = getConnection();
      o = insert(c, o, record);
      c.close();
      c = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeConnectionFinally(c);
    }
    return o;
  }
 
  /**
   * Add an object to the database
   * @param c the connection to use, expected to be open and established
   * @param o object to add
   * @param record reference to object to use to map between object and database
   * @return  the object that was added
   */
  public Object insert(Connection c, Object o, Record record) {
    Object addedObject = null;
    PreparedStatement ps = null;
    try {
      ps = record.getInsertStatment(c, o);
      ps.executeUpdate();
      ps.close();
      ps = null;
      addedObject = o;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeStatementFinally(ps);
    }
    return addedObject;
  }
  
  /* --------------------------------- updates --------------------- */
 
  /**
   * update an object in the database
   *
   * <p>Use this method for single updates. In cases where
   * several subsequent updates for objects of the same class
   * are required the use of method <code>update(Object, Record)</code>
   * is recommended instead to minimise instantiation
   * overhead.</p>
   *
   * @param o  object to update
   * @return  the object that was updated
   */
  public Object update(Object o) {
    return update(o, new GenericRecord(o.getClass()));
  }
 
  /**
   * update an object in the database
   *
   * <p>Use this method for single updates. In cases where
   * several subsequent updates for objects of the same class
   * are required the use of method <code>update(Connection, Object, Record)</code>
   * is recommended instead to minimise instantiation
   * overhead.</p>
   *
   * @param c the connection to use, expected to be open and established
   * @param o object to update
   * @return  the object that was updated
   */
  public Object update(Connection c, Object o) {
    return update(c, o, new GenericRecord(o.getClass()));
  }
 
  /**
   * update an object in the database
   * @param o object to update
   * @param record reference to object to use to map between object and database
   * @return  the object that was updated
   */
  public Object update(Object o, Record record) {
    Connection c = null;
    try {
      c = getConnection();
      o = update(c, o, record);
      c.close();
      c = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeConnectionFinally(c);
    }
    return o;
  }
 
  /**
   * update an object in the database
   * @param c the connection to use, expected to be open and established
   * @param o object to update
   * @param record reference to object to use to map between object and database
   * @return  the object that was updated
   */
  public Object update(Connection c, Object o, Record record) {
    Object updatedObject = null;
    PreparedStatement ps = null;
    try {
      ps = record.getUpdateStatment(c, o);
      ps.executeUpdate();
      ps.close();
      ps = null;
      updatedObject = o;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeStatementFinally(ps);
    }
    return updatedObject;
  }
  
  /* --------------- selects ---------------- */
 
  /**
   * Select a list of objects through a given SQL statement
   * @param sql  sql query string that designates the requested objects
   * @param record object to use to map db records to objects
   * @return a list of objects that match the given query
   */
  public List<Object> select(String sql, Record record) {
    return select(sql, record, Record.WITH_BLOBS);
  }
 
  /**
   * Select a list of objects through a given SQL statement
   * @param sql  sql query string that designates the requested objects
   * @param record  object to use to map db records to objects
   * @param includeBlobs  true when BLOB contents are to be retrieved, false if not
   * @return  a list of objects that match the given query
   */
  public List<Object> select(String sql, Record record, boolean includeBlobs) {
    Connection c = null;
    ArrayList<Object> list = new ArrayList<Object>();
    try {
      c = getConnection();
      list = (ArrayList<Object>) select(c, sql, record, includeBlobs);
      c.close();
      c = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeConnectionFinally(c);
    }
    return list;
  }
 
  /**
   * Select a list of objects through a given SQL statement
   * @param sql  sql query string that designates the requested objects
   * @param record  object to use to map db records to objects
   * @param includeBlobs  true when BLOB contents are to be retrieved, false if not
   * @param params  list of parameters in the order they appear in the SQL string
   * @return  a list of objects that match the given query
   */
  public List<Object> select(String sql, Record record, boolean includeBlobs, Object... params) {
    Connection c = null;
    ArrayList<Object> list = new ArrayList<Object>();
    try {
      c = getConnection();
      list = (ArrayList<Object>) select(c, sql, record, includeBlobs, params);
      c.close();
      c = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeConnectionFinally(c);
    }
    return list;
  }
 
  /**
   * Select a list of objects that match a given SQL statement
   * @param c  the database connection to use for this query, expected to be established and open already
   * @param sql  sql query string that designates the requested objects
   * @param record  object to use to map db records to objects
   * @param includeBlobs  true when BLOB contents are to be retrieved, false if not
   * @return  a list of objects that match the given query
   */
  public List<Object> select(Connection c, String sql, Record record, boolean includeBlobs) {
    PreparedStatement ps = null;
    ResultSet rs = null;
    ArrayList<Object> list = new ArrayList<Object>();
    try {
      ps = c.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      rs = ps.executeQuery();
      if (rs.first()) {
        while (!rs.isAfterLast()) {
          list.add(record.toObject(rs, includeBlobs));
          rs.next();
        }
      }
      rs.close();
      rs = null;
      ps.close();
      ps = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeResultSetFinally(rs);
      closeStatementFinally(ps);
    }
    return list;
  }
 
  /**
   * Select a list of objects that match a given SQL statement
   * @param c  the database connection to use for this query, expected to be established and open already
   * @param sql  sql query string that designates the requested objects
   * @param record  object to use to map db records to objects
   * @param includeBlobs  true when BLOB contents are to be retrieved, false if not
   * @param params  list of parameters in the order they appear in the SQL string
   * @return  a list of objects that match the given query
   */
  public List<Object> select(Connection c, String sql, Record record, boolean includeBlobs, Object... params) {
    PreparedStatement ps = null;
    ResultSet rs = null;
    ArrayList<Object> list = new ArrayList<Object>();
    try {
      //ps = c.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      ps = buildQuery(c, sql, params);
      rs = ps.executeQuery();
      if (rs.first()) {
        while (!rs.isAfterLast()) {
          list.add(record.toObject(rs, includeBlobs));
          rs.next();
        }
      }
      rs.close();
      rs = null;
      ps.close();
      ps = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeResultSetFinally(rs);
      closeStatementFinally(ps);
    }
    return list;
  }
 
 
  /**
   * Select a list of objects that match a given SQL statement
   * @param sql  sql query string that designates the requested objects
   * @return  a list of map objects, one for each record. An element in the
   * list can be accessed with list.get(recordno).get("fieldname")
   */
  public List<Map<String, Object>> select(String sql) {
    //Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).finest(sql);
    Connection c = null;
    List<Map<String, Object>> list = null;
    try {
      c = getConnection();
      list = select(c, sql);
      c.close();
      c = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeConnectionFinally(c);
    }
    return list;
  }
 
  /**
   * Select a list of objects that match a given SQL statement
   * @param sql  sql query string that designates the requested objects
   * @param includeBlobs true when content of blob coloumns should be returned, false if not
   * @return  a list of list objects, one for each record. An element in the
   * list can be accessed with list.get(recordno).get(fieldno), each element is of type String
   */
  public List<List<String>> select(String sql, boolean includeBlobs) {
    Connection c = null;
    List<List<String>> list = null;
    try {
      c = getConnection();
      list = select(c, sql, includeBlobs);
      c.close();
      c = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeConnectionFinally(c);
    }
    return list;
  }
 
  /**
   * Select a list of objects that match a given SQL statement
   * @param c  the database connection to use for this query, expected to be established and open already
   * @param sql  sql query string that designates the requested objects
   * @return  a list of map objects, one for each record. An element in the
   * list can be accessed with list.get(recordno).get("fieldname")
   */
  public List<Map<String, Object>> select(Connection c, String sql) {
    PreparedStatement ps = null;
    ResultSet rs = null;
    List<Map<String, Object>> list = null;
    try {
      ps = c.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      rs = ps.executeQuery();
      list = toList(rs);
      rs.close();
      rs = null;
      ps.close();
      ps = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeResultSetFinally(rs);
      closeStatementFinally(ps);
    }
    return list;
  }
 
  /**
   * Select a list of objects that match a given SQL statement
   * @param c  the database connection to use for this query, expected to be established and open already
   * @param sql  sql query string that designates the requested objects
   * @param includeBlobs true when content of blob coloumns should be returned, false if not
   * @return  a list of list objects, one for each record. An element in the
   * list can be accessed with list.get(recordno).get(fieldno), each element is of type String
   */
  public List<List<String>> select(Connection c, String sql, boolean includeBlobs) {
    PreparedStatement ps = null;
    ResultSet rs = null;
    List<List<String>> list = null;
    try {
      ps = c.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      rs = ps.executeQuery();
      list = toList(rs, includeBlobs);
      rs.close();
      rs = null;
      ps.close();
      ps = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeResultSetFinally(rs);
      closeStatementFinally(ps);
    }
    return list;
  }
 
  /**
   * Select a list of objects that match a given SQL statement
   * @param sql  sql query string that designates the requested objects with ? at the position of params
   * @param includeBlobs true when content of blob coloumns should be returned, false if not
   * @param params list of parameters in the order they appear in the SQL string
   * @return  a list of list objects, one for each record. An element in the
   * list can be accessed with list.get(recordno).get(fieldno), each element is of type String
   */
  public List<List<String>> select(String sql, boolean includeBlobs, Object... params) {
    Connection c = null;
    List<List<String>> list = null;
    try {
      c = getConnection();
      list = select(c, sql, includeBlobs, params);
      c.close();
      c = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeConnectionFinally(c);
    }
    return list;
  }
  
  /**
   * Select a list of objects that match a given SQL statement
   * @param c  the database connection to use for this query, expected to be established and open already
   * @param sql  sql query string that designates the requested objects with ? at the position of params
   * @param includeBlobs true when content of blob coloumns should be returned, false if not
   * @param params list of parameters in the order they appear in the SQL string
   * @return  a list of list objects, one for each record. An element in the
   * list can be accessed with list.get(recordno).get(fieldno), each element is of type String
   */
  public List<List<String>> select(Connection c, String sql, boolean includeBlobs, Object... params) {
    PreparedStatement ps = null;
    ResultSet rs = null;
    List<List<String>> list = null;
    try {
      ps = buildQuery(c, sql, params);
      rs = ps.executeQuery();
      list = toList(rs, includeBlobs);
      rs.close();
      rs = null;
      ps.close();
      ps = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeResultSetFinally(rs);
      closeStatementFinally(ps);
    }
    return list;
  }
  
  /* ------------------ generic SQL execution ---------- */
 
  /**
   * Execute an SQL statement and return keys generated in the database
   * @param sql  the statement to execute
   * @return  a list of generated keys
   */
  public List<Map<String, Object>> executeWithKeys(String sql) {
    List<Map<String, Object>> keys = null;
    Connection c = null;
    try {
      c = getConnection();
      keys = executeWithKeys(c, sql);
      c.close();
      c = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeConnectionFinally(c);
    }
    return keys;
  }
 
  /**
   * Execute an SQL statement and return keys generated in the database
   * @param c  database connection to use
   * @param sql  the statement to execute
   * @return  a list of generated keys
   */
  public List<Map<String, Object>> executeWithKeys(Connection c, String sql) {
    List<Map<String, Object>> keys = null;
    Statement s = null;
    try {
      s = c.createStatement();
      s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
      keys = toList(s.getGeneratedKeys());
      s.close();
      s = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeStatementFinally(s);
    }
    return keys;
  }
 
  /**
   * Execute an SQL statement
   * @param sql  the statement to execute
   * @return  the number of records affected by this statement or -1 if none
   */
  public int execute(String sql) {
    int numRows = -1;
    Connection c = null;
    try {
      c = getConnection();
      numRows = execute(c, sql);
      c.close();
      c = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeConnectionFinally(c);
    }
    return numRows;
  }
 
  /**
   * Execute an SQL statement
   * @param c  database connection to use
   * @param sql  the statement to execute
   * @return  the number of records affected by this statement or -1 if none
   */
  public int execute(Connection c, String sql) {
    int numRows = -1;
    Statement s = null;
    try {
      s = c.createStatement();
      numRows = s.executeUpdate(sql);
      s.close();
      s = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeStatementFinally(s);
    }
    return numRows;
  }
 
  /**
   * Execute an SQL statement
   * @param sql the SQL string with ? at the position of params
   * @param params list of parameters in the order they appear in the SQL string
   * @return  the number of records affected by this statement or -1 if none
   */
  public int execute(String sql, Object... params) {
    int numRows = -1;
    Connection c = null;
    try {
      c = getConnection();
      numRows = execute(c, sql, params);
      c.close();
      c = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeConnectionFinally(c);
    }
    return numRows;
  }
 
  /**
   * Execute an SQL statement
   * @param c  database connection to use
   * @param sql the SQL string with ? at the position of params
   * @param params list of parameters in the order they appear in the SQL string
   * @return  the number of records affected by this statement or -1 if none
   */
  public int execute(Connection c, String sql, Object... params) {
    int numRows = -1;
    Statement s = null;
    try {
      //s = c.createStatement();
      s = buildQuery(c, sql, params);
      if(s != null && s instanceof PreparedStatement) {
        PreparedStatement ps = (PreparedStatement) s;
        numRows = ps.executeUpdate();
        ps.close();
      }
      s = null;
    } catch (Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeStatementFinally(s);
    }
    return numRows;
  }
  
  /**
   * Execute an SQL script
   * @param sqlScript  the SQL script to execute
   * @return an array of row counts referring to the number of affected rows of 
   * each sql statement in the script in the order of SQL commands in the script 
   * Statement.EXECUTE_FAILED indicates failure of single steps in the script 
   * Statement.SUCCESS_NO_INFO indicates successful execution without information 
   * about the number of affected rows
   */
  public int[] executeScript(String sqlScript) {
    int[] ergebnisse = null;
    Connection c = null;
    Statement s = null;
    try {
      c = getConnection();
      s = c.createStatement();
      String[] sqlKommandos = sqlScript.split(";");
      for(int i = 0; i < sqlKommandos.length; i++) {
        s.addBatch(sqlKommandos[i]);
      }
      ergebnisse = s.executeBatch();
    } catch(Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeStatementFinally(s);
      closeConnectionFinally(c);
    }
    return ergebnisse;
  }
  
  /**
   * Execute an SQL script
   * @param c  the Connection object to use
   * @param sqlScript  the SQL script to execute
   * @return an array of row counts referring to the number of affected rows of 
   * each sql statement in the script in the order of SQL commands in the script 
   * Statement.EXECUTE_FAILED indicates failure of single steps in the script 
   * Statement.SUCCESS_NO_INFO indicates successful execution without information 
   * about the number of affected rows
   */
  public int[] executeScript(Connection c, String sqlScript) {
    int[] ergebnisse = null;
    Statement s = null;
    try {
      s = c.createStatement();
      String[] sqlKommandos = sqlScript.split(";");
      for(int i = 0; i < sqlKommandos.length; i++) {
        s.addBatch(sqlKommandos[i]);
      }
      ergebnisse = s.executeBatch();
    } catch(Exception ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      closeStatementFinally(s);
    }
    return ergebnisse;
  }
  
  /* -------- transactions ------------ */
  
  /*
      24.4.2013: BaseLink wurde um Transaktionen erweitert, 
      sodass Start und Ende von Transaktionen jeweils mit einer Zeile Code 
      moeglich ist.
      
      Connection c = getConnection();
      startTransaction(c);
      // ...hier Daten anlegen und verknuepfen...
      commit(c);
      startTransaction(c);
      // ...hier Daten anlegen und verknuepfen...
      commit(c);
      closeConnectionFinally(c);
      
  */
  
  
  public void startTransaction(Connection c) {
    try {
      c.setAutoCommit(false);
    } catch(SQLException ex) {
      logger.log(Level.SEVERE, ex.getMessage(), ex);
    } finally {
      // ..
    }
  }
  
  public void commit(Connection c) {
    try {
      c.commit();
    } catch(SQLException ex) {
      logger.log(Level.SEVERE, ex.getMessage(), ex);
    } finally {
      try {
        c.setAutoCommit(true);
      } catch (SQLException ex) {
        logger.log(Level.SEVERE, ex.getMessage(), ex);
      }
    }
  }
  
  public void rollback(Connection c) {
    try {
      c.rollback();
    } catch(SQLException ex) {
      logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    } finally {
      try {
        c.setAutoCommit(true);
      } catch (SQLException ex) {
        logger.log(Level.SEVERE, ex.getMessage(), ex);
      }
    }
  }
  
  /* -------- closing methods --------- */
 
  /**
   * Close a given result set
   * @param rs  the result set to close
   */
  public void closeResultSetFinally(ResultSet rs) {
    if (rs != null) {
      try {
        rs.close();
        rs = null;
      } catch (SQLException ex) {
        logger.log(Level.SEVERE, ex.getMessage(), ex);
      }
    }
  }
 
  /**
   * Close a given statement
   * @param s  the statement to close
   */
  public void closeStatementFinally(Statement s) {
    if (s != null) {
      try {
        s.close();
        s = null;
      } catch (SQLException ex) {
        logger.log(Level.SEVERE, ex.getMessage(), ex);
      }
    }
  }
 
  /**
   * close a given connection
   * @param c  the connection to close
   */
  public void closeConnectionFinally(Connection c) {
    if (c != null) {
      try {
        c.close();
        c = null;
      } catch (SQLException ex) {
        logger.log(Level.SEVERE, ex.getMessage(), ex);
      }
    }
  }
  
  /* ----------------------- helper methods -------------------------- */
  
  /**
   * Create an SQL statement from an SQL string and an array of parameters
   * @param sql the SQL string with ? at the position of params
   * @param params list of parameters in the order they appear in the SQL string
   * @return the SQL statement with given parameters applied
   */
  public PreparedStatement buildQuery(Connection c, String sql, Object[] params) throws Exception {
    PreparedStatement ps =
      c.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    for(int i= 0; i < params.length; i++) {
      //buildQueryParam(ps, params[i], i);
      ps.setObject(i+1, params[i]);
    }
    return ps;
  }
    
  /**
   * Helper method that converts a ResultSet into a list of lists, one per row,
   * each row is a list of strings
   *
   * @param rs  result set to convert
   * @param includeBlobs  true when blob columns should be returned, false if not
   * @return a list of list objects, one for each record. An element in the
   * list can be accessed with list.get(recordno).get(fieldno), each element is of type String.
   * This first row has the field names
   */
  public List<List<String>> toList(ResultSet rs, boolean includeBlobs) throws SQLException {
    List<List<String>> rows = new ArrayList<List<String>>();
    ResultSetMetaData meta = rs.getMetaData();
    int columnCount = meta.getColumnCount();
    List<String> header = new ArrayList<String>();
    for (int i = 1; i <= columnCount; i++) {
      header.add(meta.getColumnName(i));
    }
    rows.add(header);
    while (rs.next()) {
      List<String> row = new ArrayList<String>();
      for (int i = 1; i <= columnCount; i++) {
        String data = null;
        if (meta.getColumnType(i) == Types.BLOB) {
          if (includeBlobs) {
            Blob blob = rs.getBlob(i);
            if(blob != null) {
              data = new String(blob.getBytes((long) 1, (int) blob.length()));
            }
          }
        } else {
          Object o = rs.getObject(i);
          if(o != null) {
            data = o.toString();
          } else {
            data = NULL_STR;
          }
          logger.finest(data.toString());
        }
        row.add(data);
      }
      rows.add(row);
    }
    return rows;
  }
 
  /**
   * Helper method that converts a ResultSet into a list of maps, one per row
   *
   * @param rs  database content to transform
   * @return list of maps, one per row, with column name as the key
   * @throws SQLException if the connection fails
   */
  private List<Map<String, Object>> toList(ResultSet rs) throws SQLException {
    List<String> wantedColumnNames = getColumnNames(rs);
    return toList(rs, wantedColumnNames);
  }
 
  /**
   * Helper method that maps a ResultSet into a list of maps, one per row
   *
   * @param rs  database content to transform
   * @param wantedColumnNames list of columns names to include in the result map
   * @return list of maps, one per column row, with column names as keys
   * @throws SQLException if the connection fails
   */
  private List<Map<String, Object>> toList(ResultSet rs, List<String> wantedColumnNames) throws SQLException {
    // TODO BLOB handling
    List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
    int numWantedColumns = wantedColumnNames.size();
    while (rs.next()) {
      Map<String, Object> row = new TreeMap<String, Object>();
      for (int i = 0; i < numWantedColumns; ++i) {
        String columnName = wantedColumnNames.get(i);
        Object value = rs.getObject(columnName);
        if (value != null) {
          row.put(columnName, value);
          //Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).finest(columnName + " " + value);
        } else {
          row.put(columnName, "");
        }
      }
      rows.add(row);
    }
    return rows;
  }
 
  /**
   * Return all column names as a list of strings
   *
   * @param database query result set
   * @return list of column name strings
   * @throws SQLException if the query fails
   */
  private List<String> getColumnNames(ResultSet rs) throws SQLException {
    List<String> columnNames = new ArrayList<String>();
    ResultSetMetaData meta = rs.getMetaData();
    int numColumns = meta.getColumnCount();
    for (int i = 1; i <= numColumns; ++i) {
      String cName = meta.getColumnName(i);
      columnNames.add(cName);
    }
    return columnNames;
  }
}