-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJdbcUtil.java
447 lines (372 loc) · 14.5 KB
/
JdbcUtil.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
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
import java.sql.*;
import java.util.*;
import java.io.*;
import java.lang.*;
public class JdbcUtil {
static final List<String> DRIVERS;
static {
DRIVERS = new ArrayList<>();
DRIVERS.add("oracle.jdbc.driver.OracleDriver");
DRIVERS.add("com.microsoft.sqlserver.jdbc.SQLServerDriver");
DRIVERS.add("com.microsoft.sqlserver.jdbc.SQLServerConnectionPoolDataSource");
DRIVERS.add("com.mysql.jdbc.Driver");
DRIVERS.add("com.ibm.db2.jcc.DB2Driver");
DRIVERS.add("org.h2.Driver");
}
static String findDriver() {
for (String driver : DRIVERS) {
try {
System.err.println("Trying driver: " + driver);
Class.forName(driver, false, JdbcUtil.class.getClassLoader());
System.err.println("Loaded JDBC driver: [" + driver + "]");
return driver;
} catch (Exception e) {
}
}
return null;
}
static void addDriver(String driverClassName) {
System.err.println("Adding driver to the list: " + driverClassName);
DRIVERS.add(driverClassName);
}
//private final static String DB_URL = "jdbc:oracle:thin:@localhost:1521:mydatabase";
//private final static String USER = "UsernAme";
//private final static String PASS = "password123";
private static String url_base = "jdbc:oracle:thin:";
private static String username = "";
private static String password = "";
private static String url = "";
private static String _qry = null;
private static String _qryFile = null;
private static String _delim = "|";
private static boolean printBlob = false;
private static boolean hidenull = false;
private static boolean norownum = false;
private static boolean noheader = false;
private static long pagesize = -1;
private static long pageStart = 0;
private static long pageEnd = 0;
private static Connection conn = null;
public static void main(String[] args) {
parseParams(args);
if (!url.toLowerCase().startsWith("jdbc")) {
url = url_base + "@" + url;
}
try {
String driverName = findDriver();
if (driverName == null) {
System.err.println("Cannot find any known JDBC driver in the classpath.");
System.exit(1);
}
Class.forName(driverName);
readQuery();
System.err.println("Connecting to database: " + url + " using credentials: " + username + ":" + "******" + "...");
//conn = DriverManager.getConnection(DB_URL,USER,PASS);
conn = DriverManager.getConnection(url, username, password);
System.err.println("Connected");
if (_qry != null) {
for (String singleQuery : _qry.split(";")) {
sendQuery(conn, singleQuery.trim());
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
// ignore
}
}
}
}
private static void parseParams(String[] params) {
if (params.length < 3) {
System.err.println("At least 3 arguments must be provided.");
System.out.println(USAGE);
System.exit(1);
}
for (int i = 0; i < params.length; i++) {
String arg = params[i];
/* java6 is unable to switch strings */
// @formatter:off
if ("-u".equals(arg)) { username = params[++i]; } else
if ("-p".equals(arg)) { password = params[++i]; } else
if ("-U".equals(arg)) { url = params[++i]; } else
if ("-q".equals(arg)) { _qry = params[++i]; } else
if ("-d".equals(arg)) { _delim = params[++i]; } else
if ("-dr".equals(arg)) { addDriver(params[++i]); } else
if ("-if".equals(arg)) { _qryFile = params[++i]; } else
if ("-pg".equals(arg)) { parsePages(params[++i]); } else
if ("-o".equals(arg)) { parseOpt(params[++i]); } else
{
System.err.println("Unknown argument: " + arg);
System.err.println(USAGE);
System.exit(1);
}
// @formatter:on
}
}
private static void parseOpt(String option) {
if (option == null || option.isEmpty()) return;
if ("blob".equals(option)) {
printBlob = true;
} else if ("nonull".equals(option)) {
hidenull = true;
} else if ("norownum".equals(option)) {
norownum = true;
} else if ("noheader".equals(option)) {
noheader = true;
}
}
private static void parsePages(String expr) {
if (expr == null || expr.isEmpty()) {
return;
}
String pagesizeStr = "0";
String pageStartStr = "1";
String pageEndStr = "1";
long _pagesize = 0;
long _pageStart = 0;
long _pageEnd = 0;
String[] tokens = expr.split(":");
if (tokens != null && tokens.length > 0) {
if (tokens.length > 1) {
pagesizeStr = tokens[1];
if (pagesizeStr != null && !pagesizeStr.isEmpty()) {
_pagesize = Long.parseLong(pagesizeStr);
}
}
tokens = tokens[0].split("-");
if (tokens != null && tokens.length > 0) {
pageStartStr = tokens[0];
pageEndStr = pageStartStr;
if (tokens.length > 1) {
pageEndStr = tokens[1];
}
if (pageStartStr != null && ! pageStartStr.isEmpty()) {
_pageStart = Long.parseLong(pageStartStr);
} else {
_pageStart = 0;
}
if (pageEndStr != null && ! pageEndStr.isEmpty()) {
_pageEnd = Long.parseLong(pageEndStr);
} else {
_pageEnd = pageStart;
}
}
}
if (_pageStart > _pageEnd) {
throw new IllegalStateException("Starting page number cannot be lower than ending page");
}
System.err.println(String.format("Start page: %s, end page: %s, page size: %s", _pageStart, _pageEnd, _pagesize));
pagesize = _pagesize;
pageStart = _pageStart;
pageEnd = _pageEnd;
}
private static String readQuery() {
InputStream is = null;
if (_qryFile == null || _qryFile.isEmpty()) {
return _qry;
}
if ("--".equals(_qryFile)) {
System.err.println("Reading query from stdin");
try {
_qry = inputStreamToString(System.in);
} catch (Exception e) {
e.printStackTrace();
}
return _qry;
}
if (_qryFile.startsWith("file://")) {
System.err.println("Reading query from file: " + _qryFile);
_qryFile = _qryFile.split("file://")[1];
try {
is = new FileInputStream(_qryFile);
_qry = inputStreamToString(is);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeQuietly(is);
}
return _qry;
}
return null;
}
private static String inputStreamToString(InputStream inputStream) throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
// StandardCharsets.UTF_8.name() > JDK 7
try {
return result.toString("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
private static void sendQuery(Connection connection, String qry) {
String qry_low = qry.toLowerCase();
// qry = qry.toLowerCase();
if (qry_low.startsWith("select")) {
System.err.println("Sending query: [" + qry + "]");
sendSelectQuery(connection, qry);
} else if (qry_low.startsWith("insert")) {
sendInsertQuery(connection, qry);
} else if (qry_low.startsWith("show")) {
sendSelectQuery(connection, qry);
} else if (qry_low.startsWith("update")) {
if (!qry_low.contains(" where ")) {
System.err.println("WHERE clause is missing.");
System.exit(4);
}
sendUpdateQuery(connection, qry);
} else if (qry_low.startsWith("delete")) {
if (!qry_low.contains(" where ")) {
System.err.println("WHERE clause is missing.");
System.exit(4);
}
sendDeleteQuery(connection, qry);
} else {
System.err.println("Unrecognized query: [" + qry + "]");
}
}
private static void sendSelectQuery(Connection connection, String query) {
ResultSet rs = null;
try {
Statement stmt = connection.createStatement();
rs = stmt.executeQuery(query);
ResultSetMetaData meta = rs.getMetaData();
int colsCnt = meta.getColumnCount();
int rownum = 0;
String data;
long currentPage = 0;
long currentPageRow = -1;
if (noheader == false) {
System.out.print("Row#");
for (int i = 1; i <= colsCnt; i++) {
System.out.print(_delim + meta.getColumnName(i));
}
System.out.println();
}
String nulltext = "(null)";
String delim = "";
if (hidenull) {
nulltext = "";
}
while (rs.next()) {
rownum++;
currentPageRow++;
if (currentPageRow == pagesize) {
currentPage++;
currentPageRow = 0;
if (currentPage >= pageStart && currentPage <= pageEnd) {
System.err.println("Page #"+currentPage);
}
}
if (currentPage >= pageStart) {
if (currentPage > pageEnd) {
System.err.println("End of last page: #"+pageEnd);
break;
}
} else {
continue;
}
delim = "";
if (norownum == false) {
System.out.print(rownum);
delim = _delim;
}
for (int i = 1; i <= colsCnt; i++) {
Object value = rs.getObject(i);
if (value == null) {
System.out.print(delim + nulltext);
} else if (java.sql.Blob.class.isAssignableFrom(value.getClass())) {
if (printBlob) {
try {
java.sql.Blob blob = (java.sql.Blob) value;
System.out.println(delim + encodeBase64(blob.getBytes(1, (int)blob.length())));
} catch (Exception e) {
e.printStackTrace();
System.out.print(delim + "(!blob)");
}
} else {
System.out.print(delim + "(blob)");
}
} else {
System.out.print(delim + rs.getObject(i));
}
delim = _delim;
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
System.exit(3);
} finally {
try {
rs.close();
} catch (Exception ex) {
}
}
}
private static void sendUpdateQuery(Connection connection, String query) {
try {
Statement stmt = connection.createStatement();
int updatedCount = stmt.executeUpdate(query);
System.out.println("Updated rows: " + updatedCount);
} catch (Exception e) {
e.printStackTrace();
System.exit(3);
}
}
private static void sendInsertQuery(Connection connection, String query) {
try {
Statement stmt = connection.createStatement();
int updatedCount = stmt.executeUpdate(query);
System.out.println("Inserted rows: " + updatedCount);
} catch (Exception e) {
e.printStackTrace();
System.exit(3);
}
}
private static void sendDeleteQuery(Connection connection, String query) {
try {
Statement stmt = connection.createStatement();
int updatedCount = stmt.executeUpdate(query);
System.out.println("Deleted rows: " + updatedCount);
} catch (Exception e) {
e.printStackTrace();
System.exit(3);
}
}
private static void closeQuietly(Closeable closeable) {
if (closeable == null) return;
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String encodeBase64(byte[] data) {
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
return encoder.encode(data);
}
static final String USAGE = ""
+ "USAGE:\n"
+ " * -u <username>\n"
+ " * -p <password>\n"
+ " * -U <url> : e.g.: localhost:1521:mydatabase; jdbc:oracle:thin:@localhost:1521:mydatabase \n"
+ " -q <query>\n"
+ " -d <delimiter> : delimiter to separate columns in SELECT output\n"
+ " -dr <driver> : custom driver class name, e.g.: -dr 'org.h2.Driver'\n"
+ " -pg <page> : pages to select. e.g. 3-4:20 will print pages 3 and 4 of size 20. 3:20 will only print pg #3\n"
+ " -if <file> : query input file. Either 'file:///some/path/to/file.sql' or '--' for stdin\n"
+ " -o <option> : provide additional options. See docs for more info"
+ "\n";
}