comparison artifact-database/src/main/java/de/intevation/artifactdatabase/db/SQLExecutor.java @ 305:f33401ea2a6c

Artifact database: Refactorized the usage of dialect independent SQL to be reusable. artifacts/trunk@2412 c6561f87-3c4e-4783-a992-168aeb5c3f6f
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Thu, 28 Jul 2011 10:19:35 +0000
parents
children
comparison
equal deleted inserted replaced
304:40b64b4aafce 305:f33401ea2a6c
1 package de.intevation.artifactdatabase.db;
2
3 import java.sql.Connection;
4 import java.sql.PreparedStatement;
5 import java.sql.ResultSet;
6 import java.sql.SQLException;
7
8 import javax.sql.DataSource;
9
10 import org.apache.log4j.Logger;
11
12 public class SQLExecutor
13 {
14 private static Logger logger = Logger.getLogger(SQLExecutor.class);
15
16 public class Instance {
17
18 public Connection conn;
19 public PreparedStatement stmnt;
20 public ResultSet result;
21
22 public Instance() {
23 }
24
25 public void reset() throws SQLException {
26 if (result != null) {
27 result.close();
28 result = null;
29 }
30 if (stmnt != null) {
31 result = null;
32 stmnt.close();
33 }
34 }
35
36 public PreparedStatement prepareStatement(String query)
37 throws SQLException {
38 return stmnt = conn.prepareStatement(query);
39 }
40
41 public void close() {
42 if (result != null) {
43 try { result.close(); }
44 catch (SQLException sqle) {}
45 }
46 if (stmnt != null) {
47 try { stmnt.close(); }
48 catch (SQLException sqle) {}
49 }
50 if (conn != null) {
51 try { conn.close(); }
52 catch (SQLException sqle) {}
53 }
54 }
55
56 public boolean runWrite() {
57 DataSource dataSource = dbConnection.getDataSource();
58 try {
59 conn = dataSource.getConnection();
60 try {
61 conn.setAutoCommit(false);
62 return doIt();
63 }
64 catch (SQLException sqle) {
65 conn.rollback();
66 throw sqle;
67 }
68 }
69 catch (SQLException sqle) {
70 logger.error(sqle.getLocalizedMessage(), sqle);
71 }
72 finally {
73 close();
74 }
75 return false;
76 }
77
78 public boolean runRead() {
79 DataSource dataSource = dbConnection.getDataSource();
80 try {
81 conn = dataSource.getConnection();
82 return doIt();
83 }
84 catch (SQLException sqle) {
85 logger.error(sqle.getLocalizedMessage(), sqle);
86 }
87 finally {
88 close();
89 }
90 return false;
91 }
92
93 public boolean doIt() throws SQLException {
94 return true;
95 }
96 } // class Instance
97
98 protected DBConnection dbConnection;
99
100 public SQLExecutor() {
101 }
102
103 public SQLExecutor(DBConnection dbConnection) {
104 this.dbConnection = dbConnection;
105 }
106
107 public DBConnection getDBConnection() {
108 return dbConnection;
109 }
110 }
111 // vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :

http://dive4elements.wald.intevation.org