blob: 330c2a58327fbc520b98a62e466d7f0b71ce855b (
plain)
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
|
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Create a persistent database connection.
*
* @author Maurice Laveaux
*/
public class DBConnection {
/* The interface to the postgresql database connection. */
private Connection m_connection;
public DBConnection(final String hostaddress,
final String port,
final String databasename,
final String username,
final String password) {
String url = "jdbc:postgresql://" + hostaddress + ":" + port + "/" + databasename;
try {
m_connection = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
//TODO: retry when db connection fails or something.
throw new RuntimeException("cannot connect to host: " + url);
}
}
/**
* prepares a statement.
*
* @param query The query to prepare.
* @return A prepared statement.
*/
public PreparedStatement create(final String query) throws SQLException {
return m_connection.prepareStatement(query);
}
/**
* Closes the connection if it exists.
*/
public void close() {
if (m_connection != null) {
try {
m_connection.close();
} catch (SQLException ex) {
/* TODO: what to do here else. */
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
|