01 package wodbupdate;
02
03 import java.sql.*;
04
05
06 public class Database implements Databaseable {
07 protected final String connectionUrlString;
08 protected final String userName;
09 protected final String password;
10 protected Connection connection;
11
12 public Database(String aConnectionUrlString, String aUserName, String aPassword) {
13 connectionUrlString = aConnectionUrlString;
14 userName = aUserName;
15 password = aPassword;
16 }
17
18 public boolean isLocked() {
19 try {
20 Statement update = executeSQL("SELECT \"UPDATE_LOCK\" FROM \"_DBUPDATER\"");
21 ResultSet resultSet = update.getResultSet();
22 resultSet.next();
23 return resultSet.getInt(1) == 1;
24 } catch (SQLException e) {
25 e.printStackTrace();
26 return true;
27 }
28 }
29
30 public boolean tryToLock() {
31 try {
32 Statement update = executeSQL("UPDATE \"_DBUPDATER\" SET \"UPDATE_LOCK\" = 1 WHERE \"UPDATE_LOCK\" = 0");
33 return update.getUpdateCount() == 1;
34 } catch (SQLException cannotLockSQLException) {
35 return true;
36 }
37 }
38
39 public void unlock() {
40 try {
41 executeSQL("UPDATE \"_DBUPDATER\" SET \"UPDATE_LOCK\" = 0");
42 } catch (SQLException sqlException) {
43 sqlException.printStackTrace();
44 }
45 }
46
47 public int currentVersionNumber() throws SQLException {
48 Statement update = executeSQL("SELECT \"VERSION\" FROM \"_DBUPDATER\"");
49 ResultSet resultSet = update.getResultSet();
50 resultSet.next();
51 return resultSet.getInt(1);
52 }
53
54 public void setVersionNumber(int aVersionNumber) {
55 try {
56 executeSQL("UPDATE \"_DBUPDATER\" SET \"VERSION\" = " + aVersionNumber);
57 } catch (SQLException sqlException) {
58 sqlException.printStackTrace();
59 }
60 }
61
62 public Statement executeSQL(String anSQLString) throws SQLException {
63 Statement update = connection().createStatement();
64 update.execute(anSQLString);
65 return update;
66 }
67
68 protected Connection connection() throws SQLException {
69 if (connection == null) {
70 try {
71 connection = DriverManager.getConnection(connectionUrlString, userName, password);
72 } catch (SQLException e) {
73 throw new IllegalStateException("Failed to connect to the database using the update user. Please contact your DBA.");
74 }
75 }
76 return connection;
77 }
78
79 public void close() {
80 if (connection != null) {
81 try {
82 connection.close();
83 connection = null;
84 } catch (SQLException dbNotClosingSQLException) {
85 System.err.println("Failed to close JDBC connection " + dbNotClosingSQLException);
86 }
87 }
88 }
89
90 }
|