-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuery.java
265 lines (238 loc) · 7.92 KB
/
Query.java
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package bbtrial.nl.logicgate.ace;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
public class Query {
private Connection conn;
private PrintStream err;
public Query(DataSource ds) {
this(ds, System.err);
}
public Query(DataSource ds, PrintStream err) {
try {
this.conn = ds.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
this.err = err;
}
public Query(Connection conn, PrintStream err) {
this.conn = conn;
this.err = err;
}
/**
* @param query
* the SQL Query to execute
*
* @return List of "rows" represented as a Map of Column Name to Column
* Value
*/
public List<Map<String, Object>> executeQuery(String query) {
return executeQuery(query, Collections.EMPTY_LIST);
}
/**
* @param query
* the SQL Query to execute
* @param params
* the List<?> containing the parameters for the query
*
* @return List of "rows" represented as a Map of Column Name to Column
* Value
*/
public List<Map<String, Object>> executeQuery(String query, List<?> params) {
PreparedStatement pStmt = null;
ResultSet rs = null;
try {
pStmt = prepareStatement(query, params);
rs = pStmt.executeQuery();
return mapRows(rs);
} catch (SQLException sqlEx) {
throw new QueryException(query, params, sqlEx);
} finally {
close(pStmt, rs);
}
}
/**
* Returns the record count for the specified table
* @param table
* @return
*/
public int executeCount(String table){
String query = "SELECT COUNT(*) FROM " + table;
int records = 0;
PreparedStatement pStmt = null;
ResultSet rs = null;
List<?> params = Collections.EMPTY_LIST;
try {
pStmt = prepareStatement(query, params);
rs = pStmt.executeQuery();
//this result should always be a single int value
rs.next();
records = rs.getInt(1);
} catch (SQLException sqlEx) {
throw new QueryException(query, params, sqlEx);
} finally {
close(pStmt, rs);
}
return records;
}
/**
* @param query
* the SQL Query to execute
* @param params
* the List<?> containing the parameters for the query
*
* @return either a row count, or 0 for SQL commands
*/
public int executeUpdate(String query) {
return executeUpdate(query, Collections.EMPTY_LIST);
}
/**
* Executes an INSERT query
* Returns the primary keys of the affected rows as a list of strings
* @param query
*/
public List<String> executeInsert(String query) {
return executeTransaction(query);
}
/**
* Executes a transactional query, returns the keys
* of the inserted rows in a list.
* @param query
*/
private List<String> executeTransaction(String query) {
List<String> keys = null;
try {
//Switch to manual transaction mode by setting
//autocommit to false. Note that this starts the first
//manual transaction.
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
conn.commit(); //This commits the transaction and starts a new one.
keys = listKeys(stmt.getGeneratedKeys());
stmt.close(); //This turns off the transaction.
}
catch (SQLException ex) {
new WriteFile().appendFile(BriefBot.ERROR_FILE, "Unable to run query: "
+ query + "\n" + ex.getMessage() + "\n");
try {
conn.rollback();
}
catch (SQLException se) {
new WriteFile().appendFile(BriefBot.ERROR_FILE, "Unable to roll back: "
+ se.getMessage() + "\n");
}
}
return keys;
}
/**
* Converts the values of a result set to a list of Strings.
* Meant to be used when there is only a single-column result.
* @param rs
* @return keys as a list of strings
* @throws SQLException
*/
private List<String> listKeys(ResultSet rs) throws SQLException {
int cols = rs.getMetaData().getColumnCount();
List<String> rows = new ArrayList<String>();
while (rs.next()) {
for (int i = 1; i <= cols; i++) {
rows.add(rs.getObject(i).toString());
}
}
return rows;
}
/**
* @param query
* the SQL Query to execute
* @param params
* the List<?> containing the parameters for the query
*
* @return the row count (or 0 for SQL statements which return nothing)
*/
public int executeUpdate(String query, List<?> params) {
PreparedStatement pStmt = null;
try {
conn.setAutoCommit(false);
pStmt = prepareStatement(query, params);
int result = pStmt.executeUpdate();
conn.commit();
return result;
} catch (SQLException sqlEx) {
new WriteFile().appendFile(BriefBot.ERROR_FILE, "Unable to run query: "
+ query + "\n" + sqlEx.getMessage() + "\n");
throw new QueryException(query, params, sqlEx);
} finally {
close(pStmt);
}
}
//
private PreparedStatement prepareStatement(String query, List<?> params)
throws SQLException {
if (query == null) {
throw new IllegalArgumentException("query string may not be null");
}
if (query.length() == 0) {
throw new IllegalArgumentException("query string may not be empty");
}
PreparedStatement pStmt = conn.prepareStatement(query);
int numParams = pStmt.getParameterMetaData().getParameterCount();
if (numParams != params.size()) {
final String msg = "Expected " + numParams + " parameters, got "
+ params.size();
throw new IllegalArgumentException(msg);
}
for (int i = 0; i < params.size(); i++) {
Object param = params.get(i);
pStmt.setObject(i + 1, param);
}
return pStmt;
}
private List<Map<String, Object>> mapRows(ResultSet rs) throws SQLException {
int cols = rs.getMetaData().getColumnCount();
List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
while (rs.next()) {
Map<String, Object> rowVals = new LinkedHashMap<String, Object>(
cols);
for (int i = 1; i <= cols; i++) {
String columnName = rs.getMetaData().getColumnName(i);
Object columValue = rs.getObject(i);
rowVals.put(columnName, columValue);
}
rows.add(rowVals);
}
return rows;
}
private void close(Statement stmt, ResultSet rs) {
close(rs);
close(stmt);
}
private void close(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
} catch (Throwable t) {
t.printStackTrace(err);
}
}
}
private void close(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (Throwable t) {
t.printStackTrace(err);
}
}
}
}