1 package org.cacert.gigi.database;
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.PreparedStatement;
6 import java.sql.ResultSet;
7 import java.sql.SQLException;
8 import java.util.HashMap;
9 import java.util.Properties;
10 import java.sql.Statement;
12 public class DatabaseConnection {
13 public static final int CONNECTION_TIMEOUT = 24 * 60 * 60;
15 HashMap<String, PreparedStatement> statements = new HashMap<String, PreparedStatement>();
16 private static Properties credentials;
18 public DatabaseConnection() {
20 Class.forName(credentials.getProperty("sql.driver"));
21 } catch (ClassNotFoundException e) {
27 private void tryConnect() {
29 c = DriverManager.getConnection(credentials.getProperty("sql.url")
30 + "?zeroDateTimeBehavior=convertToNull",
31 credentials.getProperty("sql.user"),
32 credentials.getProperty("sql.password"));
33 PreparedStatement ps = c
34 .prepareStatement("SET SESSION wait_timeout=?;");
35 ps.setInt(1, CONNECTION_TIMEOUT);
38 adHoc = c.createStatement();
39 } catch (SQLException e) {
43 public PreparedStatement prepare(String query) throws SQLException {
45 PreparedStatement statement = statements.get(query);
46 if (statement == null) {
47 statement = c.prepareStatement(query);
48 statements.put(query, statement);
52 long lastAction = System.currentTimeMillis();
53 private void ensureOpen() {
54 if (System.currentTimeMillis() - lastAction > CONNECTION_TIMEOUT * 1000L) {
56 ResultSet rs = adHoc.executeQuery("SELECT 1");
58 lastAction = System.currentTimeMillis();
60 } catch (SQLException e) {
65 lastAction = System.currentTimeMillis();
67 public static int lastInsertId(PreparedStatement query) throws SQLException {
68 ResultSet rs = query.getGeneratedKeys();
70 int id = rs.getInt(1);
74 static ThreadLocal<DatabaseConnection> instances = new ThreadLocal<DatabaseConnection>() {
76 protected DatabaseConnection initialValue() {
77 return new DatabaseConnection();
80 public static DatabaseConnection getInstance() {
81 return instances.get();
83 public static void init(Properties conf) {
84 if (credentials != null) {
85 throw new Error("Re-initiaizing is forbidden.");
89 public void beginTransaction() throws SQLException {
90 c.setAutoCommit(false);
92 public void commitTransaction() throws SQLException {
94 c.setAutoCommit(true);
96 public void quitTransaction() {
98 if (!c.getAutoCommit()) {
100 c.setAutoCommit(true);
102 } catch (SQLException e) {