1 package org.cacert.gigi.database;
3 import java.io.FileInputStream;
4 import java.io.IOException;
5 import java.sql.Connection;
6 import java.sql.DriverManager;
7 import java.sql.PreparedStatement;
8 import java.sql.ResultSet;
9 import java.sql.SQLException;
10 import java.util.HashMap;
11 import java.util.Properties;
12 import java.sql.Statement;
14 public class DatabaseConnection {
15 public static final int CONNECTION_TIMEOUT = 24 * 60 * 60;
17 HashMap<String, PreparedStatement> statements = new HashMap<String, PreparedStatement>();
18 static Properties credentials = new Properties();
21 credentials.load(new FileInputStream("config/sql.properties"));
22 } catch (IOException e) {
27 public DatabaseConnection() {
29 Class.forName(credentials.getProperty("driver"));
30 } catch (ClassNotFoundException e) {
36 private void tryConnect() {
38 c = DriverManager.getConnection(credentials.getProperty("url")
39 + "?zeroDateTimeBehavior=convertToNull",
40 credentials.getProperty("user"),
41 credentials.getProperty("password"));
42 PreparedStatement ps = c
43 .prepareStatement("SET SESSION wait_timeout=?;");
44 ps.setInt(1, CONNECTION_TIMEOUT);
47 adHoc = c.createStatement();
48 } catch (SQLException e) {
52 public PreparedStatement prepare(String query) throws SQLException {
54 PreparedStatement statement = statements.get(query);
55 if (statement == null) {
56 statement = c.prepareStatement(query);
57 statements.put(query, statement);
61 long lastAction = System.currentTimeMillis();
62 private void ensureOpen() {
63 if (System.currentTimeMillis() - lastAction > CONNECTION_TIMEOUT * 1000L) {
65 ResultSet rs = adHoc.executeQuery("SELECT 1");
67 lastAction = System.currentTimeMillis();
69 } catch (SQLException e) {
74 lastAction = System.currentTimeMillis();
76 public static int lastInsertId(PreparedStatement query) throws SQLException {
77 ResultSet rs = query.getGeneratedKeys();
79 int id = rs.getInt(1);
83 static ThreadLocal<DatabaseConnection> instances = new ThreadLocal<DatabaseConnection>() {
85 protected DatabaseConnection initialValue() {
86 return new DatabaseConnection();
89 public static DatabaseConnection getInstance() {
90 return instances.get();