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;
19 public DatabaseConnection() {
21 Class.forName(credentials.getProperty("sql.driver"));
22 } catch (ClassNotFoundException e) {
29 private void tryConnect() {
31 c = DriverManager.getConnection(credentials.getProperty("sql.url") + "?zeroDateTimeBehavior=convertToNull",
32 credentials.getProperty("sql.user"), credentials.getProperty("sql.password"));
33 PreparedStatement ps = c.prepareStatement("SET SESSION wait_timeout=?;");
34 ps.setInt(1, CONNECTION_TIMEOUT);
37 adHoc = c.createStatement();
38 } 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, Statement.RETURN_GENERATED_KEYS);
48 statements.put(query, statement);
53 long lastAction = System.currentTimeMillis();
55 private void ensureOpen() {
56 if (System.currentTimeMillis() - lastAction > CONNECTION_TIMEOUT * 1000L) {
58 ResultSet rs = adHoc.executeQuery("SELECT 1");
60 lastAction = System.currentTimeMillis();
62 } catch (SQLException e) {
67 lastAction = System.currentTimeMillis();
70 public static int lastInsertId(PreparedStatement query) throws SQLException {
71 ResultSet rs = query.getGeneratedKeys();
73 int id = rs.getInt(1);
78 static ThreadLocal<DatabaseConnection> instances = new ThreadLocal<DatabaseConnection>() {
80 protected DatabaseConnection initialValue() {
81 return new DatabaseConnection();
85 public static DatabaseConnection getInstance() {
86 return instances.get();
89 public static boolean isInited() {
90 return credentials != null;
93 public static void init(Properties conf) {
94 if (credentials != null) {
95 throw new Error("Re-initiaizing is forbidden.");
100 public void beginTransaction() throws SQLException {
101 c.setAutoCommit(false);
104 public void commitTransaction() throws SQLException {
106 c.setAutoCommit(true);
109 public void quitTransaction() {
111 if (!c.getAutoCommit()) {
113 c.setAutoCommit(true);
115 } catch (SQLException e) {