-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnection.java
More file actions
452 lines (372 loc) · 15.5 KB
/
Connection.java
File metadata and controls
452 lines (372 loc) · 15.5 KB
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
package javaxt.sql;
import java.sql.SQLException;
import java.util.*;
//******************************************************************************
//** Connection Class
//******************************************************************************
/**
* Used to open and close a connection to a database and execute queries.
*
******************************************************************************/
public class Connection implements AutoCloseable {
private java.sql.Connection conn = null;
private Database database;
private long t;
//**************************************************************************
//** Constructor
//**************************************************************************
public Connection(){}
//**************************************************************************
//** Constructor
//**************************************************************************
public Connection(java.sql.Connection conn){
open(conn);
}
//**************************************************************************
//** isOpen
//**************************************************************************
/** Returns true if the connection is open.
*/
public boolean isOpen(){
return !isClosed();
}
//**************************************************************************
//** isClosed
//**************************************************************************
/** Returns true if the connection is closed.
*/
public boolean isClosed(){
try{
return conn.isClosed();
}
catch(Exception e){
return true;
}
}
//**************************************************************************
//** getConnectionSpeed
//**************************************************************************
/** Used to retrieve the time it took to open the database connection
* (in milliseconds)
*/
public long getConnectionSpeed(){
return t;
}
//**************************************************************************
//** getConnection
//**************************************************************************
/** Used to retrieve the java.sql.Connection for this Connection
*/
public java.sql.Connection getConnection(){
return conn;
}
//**************************************************************************
//** open
//**************************************************************************
/** Used to open a connection to the database using a JDBC connection
* string. Returns true if the connection was opened successfully.
*
* @param ConnectionString A jdbc connection string/url. All connection
* URLs have the following form:
* <pre> jdbc:[dbVendor]://[dbName][propertyList] </pre>
*
* Example:
* <pre> jdbc:derby://temp/my.db;user=admin;password=mypassword </pre>
*/
public boolean open(String ConnectionString) throws SQLException {
return open(new Database(ConnectionString));
}
//**************************************************************************
//** open
//**************************************************************************
/** Used to open a connection to the database using a javaxt.sql.Database.
* Returns true if the connection was opened successfully.
*/
public boolean open(Database database) throws SQLException {
long startTime = System.currentTimeMillis();
this.database = database;
ConnectionPool connectionPool = database.getConnectionPool();
if (connectionPool==null){
//Load JDBC Driver
java.sql.Driver Driver = (java.sql.Driver) database.getDriver().load();
//if (Conn!=null && Conn.isOpen()) Conn.close();
String url = database.getURL(false);
String username = database.getUserName();
String password = database.getPassword();
java.util.Properties properties = database.getProperties();
if (properties==null) properties = new java.util.Properties();
if (username!=null){
properties.put("user", username);
if (password!=null) properties.put("password", password);
}
conn = Driver.connect(url, properties);
}
else{
conn = connectionPool.getConnection().getConnection();
}
boolean isClosed = conn.isClosed();
t = System.currentTimeMillis()-startTime;
return !isClosed;
}
//**************************************************************************
//** open
//**************************************************************************
/** Used establish a connection to the database using a previously opened
* java.sql.Connection. Returns true if the connection is open.
* @param conn An open java.sql.Connection
* @param database Used to associate a database instance with this
* connection. In doing so, you can avoid a potentially costly call parse
* connection metadata.
*/
public boolean open(java.sql.Connection conn, Database database){
this.database = database;
return open(conn);
}
//**************************************************************************
//** open
//**************************************************************************
/** Used establish a connection to the database using a previously opened
* java.sql.Connection. Returns true if the connection is open.
*/
public boolean open(java.sql.Connection conn){
boolean isClosed;
try{
if (database==null) database = new Database(conn);
this.conn = conn;
isClosed = conn.isClosed();
}
catch(Exception e){
//System.out.println("Failed");
//System.out.println(database.getDriver().getVendor() + " ERROR: " + e.toString());
isClosed = true;
}
t = 0;
return !isClosed;
}
//**************************************************************************
//** close
//**************************************************************************
/** Used to close a connection to the database, freeing up server resources.
* It is imperative that the database connection is closed after it is no
* longer needed, especially if the connection came from a ConnectionPool.
* That said, this class implements the AutoCloseable interface so you do
* not have to call this method if the connection was opened as part of a
* "try" statement. Example:
<pre>
try (javaxt.sql.Connection conn = database.getConnection()){
}
catch(Exception e){
e.printStackTrace();
}
</pre>
*/
public void close(){
//System.out.println("Closing connection...");
if (isOpen()) {
try{conn.close();}
catch(Exception e){
//e.printStackTrace();
}
}
}
//**************************************************************************
//** getRecords
//**************************************************************************
/** Used to execute a SQL statement and returns Records as an iterator.
* Example:
<pre>
for (javaxt.sql.Record record : conn.getRecords("select id from contacts")){
System.out.println(record.get(0));
}
</pre>
* Note that records returned by this method are read-only.
*/
public Iterable<javaxt.sql.Record> getRecords(String sql) throws SQLException {
return getRecords(sql, null);
}
//**************************************************************************
//** getRecords
//**************************************************************************
/** Used to execute a SQL statement and returns a Records as an iterator.
* Example:
<pre>
for (javaxt.sql.Record record : conn.getRecords(
"select first_name, last_name from contacts",
new HashMap<String, Object>() {{
put("readOnly", true);
put("fetchSize", 1000);
}}
))
{
System.out.println(record.get("first_name") + " " + record.get("last_name"));
}
</pre>
* @param sql Query statement. This parameter is required.
* @param props Recordset options (e.g. readOnly, fetchSize, batchSize).
* See the Recordset class for more information about this properties. This
* parameter is optional.
*/
public Iterable<javaxt.sql.Record> getRecords(String sql, Map<String, Object> props) throws SQLException {
return new RecordIterator(getRecordset(sql, props));
}
//**************************************************************************
//** getRecord
//**************************************************************************
/** Returns a single record from the database. Example:
<pre>
javaxt.sql.Record record = conn.getRecord("select count(*) from contacts");
if (record!=null) System.out.println(record.get(0));
</pre>
* Note that records returned by this method are read-only.
*/
public javaxt.sql.Record getRecord(String sql) throws SQLException {
HashMap<String, Object> props = new HashMap<>();
props.put("readOnly", true);
props.put("fetchSize", 1);
javaxt.sql.Record record = null;
try (Recordset rs = getRecordset(sql, props)){
if (rs.hasNext()) record = rs.getRecord();
}
return record;
}
//**************************************************************************
//** getRecordset
//**************************************************************************
/** Used to execute a SQL statement and return an open Recordset. The caller
* must explicitly close the Recordset when finished or invoke the
* getRecordset() method it in a try/catch statement.
* @param sql Query statement. This parameter is required.
* @param props Recordset options (e.g. readOnly, fetchSize, batchSize).
* See the getRecords() method for an example of how to set properties.
* This parameter is optional.
*/
public Recordset getRecordset(String sql, Map<String, Object> props) throws SQLException {
if (props==null) props = new HashMap<>();
if (props.isEmpty()){
props.put("readOnly", true);
props.put("fetchSize", 1000);
}
Boolean readOnly = new Value(props.get("readOnly")).toBoolean();
if (readOnly==null) readOnly = true;
Integer fetchSize = new Value(props.get("fetchSize")).toInteger();
if (fetchSize==null) fetchSize = 1000;
Integer batchSize = new Value(props.get("batchSize")).toInteger();
if (batchSize==null) batchSize = 0;
Recordset rs = new Recordset();
if (readOnly) rs.setFetchSize(fetchSize);
rs.open(sql, this, readOnly);
if (!readOnly) rs.setBatchSize(batchSize);
return rs;
}
//**************************************************************************
//** getRecordset
//**************************************************************************
/** Used to execute a SQL statement and return an open Recordset. The caller
* must explicitly close the Recordset when finished or invoke the
* getRecordset() method it in a try/catch statement. Example usage:
<pre>
try (javaxt.sql.Connection conn = db.getConnection()){
//Open recordset
try (javaxt.sql.Recordset rs = conn.getRecordset("select * from contacts")){
//Iterate through the records
while (rs.next()){
//Do something with the record. Example:
System.out.println(rs.getValue(0));
}
}
}
catch(Exception e){
e.printStackTrace();
}
</pre>
* @param sql Query statement. This parameter is required.
* @param readOnly If true, will
*/
public Recordset getRecordset(String sql, boolean readOnly) throws SQLException {
HashMap<String, Object> props = new HashMap<>();
props.put("readOnly", readOnly);
if (readOnly) props.put("fetchSize", 1000);
return getRecordset(sql, props);
}
//**************************************************************************
//** getRecordset
//**************************************************************************
/** Used to execute a SQL statement and return an open Recordset. The caller
* must explicitly close the Recordset when finished or invoke the
* getRecordset() method it in a try/catch statement. See the other
* getRecordset() for an example. Note that records returned by this method
* are read-only.
*/
public Recordset getRecordset(String sql) throws SQLException {
return getRecordset(sql, true);
}
//**************************************************************************
//** execute
//**************************************************************************
/** Used to execute a prepared sql statement (e.g. "delete from my_table").
*/
public void execute(String sql) throws SQLException {
try (java.sql.PreparedStatement stmt = conn.prepareStatement(sql)){
stmt.execute();
try { conn.commit(); } catch(Exception e){}
}
}
//**************************************************************************
//** commit
//**************************************************************************
/** Used to explicitly commit changes made to the database.
*/
public void commit() throws SQLException {
execute("COMMIT");
}
//**************************************************************************
//** getDatabase
//**************************************************************************
/** Used to return database information associated with this connection.
*/
public Database getDatabase(){
return database;
}
//**************************************************************************
//** RecordIterator
//**************************************************************************
/** Class used to iterate through records in a Recordset
*/
private class RecordIterator implements Iterable<javaxt.sql.Record>, AutoCloseable {
private final Recordset rs;
public RecordIterator(Recordset rs){
this.rs = rs;
}
@Override
public java.util.Iterator<javaxt.sql.Record> iterator() {
return new java.util.Iterator<javaxt.sql.Record>(){
@Override
public boolean hasNext(){
boolean hasNext = rs.hasNext();
//Since the getRecords() returns an Iterable (vs this class),
//the close method never gets called even though we implement
//the AutoCloseable interface. Therefore, we will call the
//close() method manually if there are no other records.
if (!hasNext) close();
return hasNext;
}
@Override
public javaxt.sql.Record next(){
Field[] fields = rs.getFields();
Field[] clones = new Field[fields.length];
for (int i=0; i<fields.length; i++){
clones[i] = fields[i].clone();
clones[i].setValue(fields[i].getValue());
}
javaxt.sql.Record record = new javaxt.sql.Record(clones);
rs.moveNext();
return record;
}
};
}
@Override
public void close() {
if (rs!=null) rs.close();
}
}
}