Prof. Edwar Saliba Júnior
1 package Conexao;
2
3 /**
4 *
5 * @author Cynthia Lopes
6 * @author Edwar Saliba Júnior
7 */
8 import java.io.FileNotFoundException;
9 import java.io.IOException;
10 import java.sql.SQLException;
11 import java.sql.Statement;
12 import java.sql.Connection;
13 import java.sql.DriverManager;
14 import java.sql.ResultSet;
15 import java.io.BufferedReader;
16 import java.io.FileReader;
17 import java.util.ArrayList;
18 import java.util.logging.Level;
19 import java.util.logging.Logger;
20
21 public final class Database {
22
23
private Access informationDB;
24
private Connection connectionDB;
25
private Statement queryDB;
26
private boolean enableMessages;
27
private final String c_DATABASE_FILE = "JSP_Ex02.txt";
28
private int dbms; // Sistema Gerenciador de Banco de Dados
29
30
/**
31
* Este método retorna um número inteiro que corresponde ao Sistema Gerenciador
32
* de Banco de Dados que está sendo tratado pela classe Database. O valor a
33
* ser retornado poderá ser:
34
* 1 - quando o SGBD utilizado for o PostgreSQL e
35
* 2 - quando o SGBD utilizado for o MySQL.
36
*/
37
public int getDbms() {
38
return dbms;
39
}
40
41
/**
42
* Este método configura um parâmetro importante para se trabalhar com a
43
* classe Database, nele deve-se escolher entre dois tipos de Sistemas
44
* Gerenciadores de Banco de Dados (PostgreSQL e MySQL). O valor a ser
45
* passado para o parâmetro "sgdb" deverá ser:
46
* 1 - quando o SGBD utilizado for o PostgreSQL e
47
* 2 - quando o SGBD utilizado for o MySQL.
48
* @param dbms
49
*/
50
public void setDbms(int
(int dbms) {
51
this.dbms = dbms;
52
}
53
54
public Database()
() throws FileNotFoundException, ClassNotFoundException {
55
56
FileReader file = new FileReader(c_DATABASE_FILE);
57
BufferedReader reader = new BufferedReader(file);
58
59
String dataBaseName;
60
try {
61
dataBaseName = reader.readLine();
62
String password = reader.readLine();
63
String host = reader.readLine();
64
65
reader.close();
66
file.close();
67
68
this.informationDB = new Access(dataBaseName, password, host);
69
this.connectionToDB();
70
this.enableMessages = true;
71
72
// Valor padrão para o atributo é o SGBD PostgreSQL.
73
this.dbms = 1;
74
} catch (IOException ex) {
75
Logger.getLogger(Database.class.getName()).log(Level.
Logger.
(Database.class.getName()).log(Level.SEVERE , null, ex);
(Database.class.getName()).log(Level.
76
}
77
}
78
79
public Database(String
(String dataBaseName, String password, String host) {
80
try {
81
this.informationDB = new Access(dataBaseName, password, host);
82
this.connectionToDB();
83
this.enableMessages = false;
84
} catch (Exception ex) {
85
Logger.getLogger(Database.class.getName()).log(Level.
Logger.
(Database.class.getName()).log(Level.SEVERE , null, ex);
(Database.class.getName()).log(Level.
86
}
87
}
88
89
public Database(Access
(Access info) {
1.1 of 7
2013.06.18 16:01:02
Prof. Edwar Saliba Júnior
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
public Database(Access
(Access info) {
this.informationDB = info;
this.enableMessages = false;
}
/**
* O parâmetro "tipoBanco" deve receber: - 1 para PostgreSQL - 2 para MySQL
*
* @param tipoBanco (int)
* @throws ClassNotFoundException
*/
public void connectionToDB()
() throws ClassNotFoundException {
try {
this.startDriver();
connectionDB = DriverManager.getConnection(
DriverManager.
this.informationDB.getURL(),
this.informationDB.getUsuario(),
this.informationDB.getSenha());
if (this.enableMessages) {
System.out.println("Connection
System.
.println("Connection with database '"
+ this.informationDB.getNomeBD() + "' sucess completed.");
}
this.queryDB = this.connectionDB.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE ,
ResultSet.
ResultSet.CONCUR_READ_ONLY );
ResultSet.
} catch (SQLException e) {
System.out.println(e.toString());
System.
.println(e.toString());
}
}
public void startDriver()
() throws ClassNotFoundException {
switch (dbms) {
case 1:
Class.forName("org.postgresql.Driver");
Class.
("org.postgresql.Driver");
break;
case 2:
Class.forName("com.mysql.jdbc.Driver");
Class.
("com.mysql.jdbc.Driver");
}
}
public void insertValues(String
(String tableName, String fieldsNames[],
String fieldsValues[]) throws SQLException {
String query;
boolean putQuotationMarks;
putQuotationMarks = dbms == 1;
if (putQuotationMarks) {
query = "INSERT INTO \""
" + tableName + "\"
"
(";
query += returnFieldsNames(fieldsNames) + ")";
query += " VALUES(";
query += returnValues(fieldsValues, true) + ")";
} else {
query = "INSERT INTO " + tableName + " (";
query += returnFieldsNames(fieldsNames) + ")";
query += " VALUES(";
query += returnValues(fieldsValues, true) + ")";
}
if (this.enableMessages) {
System.out.println(query);
System.
.println(query);
}
this.queryDB.execute(query);
if (dbms == 1) {
this.connectionDB.commit();
}
}
public void deleteValues(String
(String tableName, String condition) throws SQLException {
String query;
if (dbms == 1) {
query = "DELETE FROM \""
" + tableName + "\"";
"
} else {
query = "DELETE FROM " + tableName + " ";
}
2.1 of 7
if (!condition.equals("")) {
query += " WHERE " + condition;
}
if (this.enableMessages) {
System.out.println(query);
System.
.println(query);
}
this.queryDB.execute(query);
if (dbms == 1) {
2013.06.18 16:01:02
Prof.
Edwar
Saliba Júnior
177
if (dbms == 1) {
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
this.connectionDB.commit();
}
}
public void updateValues(String
(String tableName, String fields[], String values[],
String condition) throws SQLException {
String query;
if (dbms == 1) {
query = "UPDATE \""
" + tableName + "\"
"
query += this.returnSetValues(fields,
} else {
query = "UPDATE " + tableName + " SET
query += this.returnSetValues(fields,
}
if (!condition.equals("")) {
query += " WHERE " + condition;
}
SET ";
values, true);
";
values, false);
if (this.enableMessages) {
System.out.println(query);
System.
.println(query);
}
this.queryDB.execute(query);
if (dbms == 1) {
this.connectionDB.commit();
}
}
public boolean existRow(String
(String table, String condition) throws SQLException {
boolean foundRow;
String query = "SELECT 1 ";
query += " FROM \""
" + table + "\"";
"
if (!condition.equals("")) {
query += " WHERE " + condition;
}
ResultSet resultSet = this.queryDB.executeQuery(query);
foundRow = resultSet.first();
if (this.enableMessages) {
System.out.println(query);
System.
.println(query);
}
return (foundRow);
}
public void printSelection(String
(String table, String fields[], String condition)
throws SQLException {
String query = "SELECT ";
query += returnFieldsNames(fields);
query += " FROM \""
" + table + "\"";
"
if (!condition.equals("")) {
query += " WHERE " + condition;
}
ResultSet resultSet = this.queryDB.executeQuery(query);
if (this.enableMessages) {
System.out.println(query);
System.
.println(query);
}
while (resultSet.next()) {
String print = "";
for (int i = 0; i < fields.length; i++) {
print += "|" + resultSet.getString(fields[i]) + "|\t";
"|
}
System.out.println(print);
System.
.println(print);
}
}
public ArrayList selection(String
(String table, boolean putQuotationMarksOnTheFields,
String fields[], String condition) {
ArrayList resultsList = new ArrayList();
3.1 of 7
try {
String query = "SELECT ";
if (putQuotationMarksOnTheFields) {
query += returnFieldsNames(fields);
} else {
query += returnValues(fields, putQuotationMarksOnTheFields);
}
query += " FROM " + table;
2013.06.18 16:01:02
Prof.
Edwar
Saliba Júnior
265
query += " FROM " + table;
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
if (!condition.equals("")) {
query += " WHERE " + condition;
}
ResultSet resultSet = this.queryDB.executeQuery(query);
if (this.enableMessages) {
System.out.println(query);
System.
.println(query);
}
resultSet.beforeFirst();
while (resultSet.next()) {
String[] row = new String[resultSet.getMetaData().getColumnCount()];
for (int i = 0; i < resultSet.getMetaData().getColumnCount(); i++) {
row[i] = resultSet.getString(i + 1);
}
resultsList.add(row);
}
} catch (SQLException ex) {
System.out.println("Exceção
System.
.println("Exceção SQL: " + ex);
}
return resultsList;
}
public ResultSet selection(String
(String table, String fields[],
boolean putQuotationMarksOnTheFields, String condition,
boolean pointerToFirstRecord) throws SQLException {
String query = "SELECT ";
if (putQuotationMarksOnTheFields) {
query += returnFieldsNames(fields);
if (dbms == 1) {
query += " FROM \""
" + table + "\"";
"
} else {
query += " FROM " + table + " ";
}
} else {
query += returnValues(fields, putQuotationMarksOnTheFields);
query += " FROM " + table;
}
if (!condition.equals("")) {
query += " WHERE " + condition;
}
ResultSet resultSet = this.queryDB.executeQuery(query);
if (pointerToFirstRecord) {
resultSet.next();
}
return (resultSet);
}
public ResultSet selection(String
(String query) throws SQLException {
ResultSet resultSet = this.queryDB.executeQuery(query);
resultSet.next();
return (resultSet);
}
public void printJoinSelection(String
(String tables[], String fields[],
String condition) throws SQLException {
String query = "SELECT ";
query += returnFieldsNames(fields);
query += " FROM " + returnFieldsNames(tables);
4.1 of 7
if (!condition.equals("")) {
query += " WHERE " + condition;
}
ResultSet resultSet = this.queryDB.executeQuery(query);
if (this.enableMessages) {
System.out.println(query);
System.
.println(query);
}
for (int i = 0; i < fields.length; i++) {
int dotPosition = fields[i].indexOf('.');
fields[i] = fields[i].substring(dotPosition + 1, fields[i].length());
}
while (resultSet.next()) {
String print = "";
for (int i = 0; i < fields.length; i++) {
print += "|" + resultSet.getString(fields[i]) + "|\t";
"|
}
2013.06.18 16:01:02
Prof. Edwar Saliba Júnior
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
System.out.println(print);
System.
.println(print);
}
}
public String returnValues(String
(String values[], boolean putQuotationMarks) {
String vals = "";
if (putQuotationMarks) {
for (int i = 0; i < values.length - 1; i++) {
vals += "\'"
" " + values[i] + "\',
"
";
}
vals += "\'"
" " + values[values.length - 1] + "\'";
"
} else {
for (int i = 0; i < values.length - 1; i++) {
vals += values[i] + ", ";
}
vals += values[values.length - 1];
}
return vals;
}
public String returnFieldsNames(String
(String values[]) {
boolean putQuotationMarks;
putQuotationMarks = dbms == 1;
String vals;
if (putQuotationMarks) {
vals = "\"";
"
for (int i = 0; i < values.length - 1; i++) {
vals += values[i] + "\",
"
\"";
}
vals += values[values.length - 1] + "\"";
"
} else {
vals = "";
for (int i = 0; i < values.length - 1; i++) {
vals += values[i] + ", ";
}
vals += values[values.length - 1];
}
return vals;
}
public String returnSetValues(String
(String fields[], String values[],
boolean putQuotationMarks) {
String vals = "";
for (int i = 0; i < values.length - 1; i++) {
if (putQuotationMarks) {
vals += "\""
" " + fields[i] + "\"
"
= "
+ (values[i].equals("") ? "\'
" '\'" : "\'"
+ values[i] + "\'")
"
+ ", ";
} else {
vals += "" + fields[i] + " = "
+ (values[i].equals("") ? "\'
" '\'" : "\'"
+ values[i] + "\'")
"
+ ", ";
}
}
if (putQuotationMarks) {
vals += "\""
" " + fields[fields.length - 1] + "\"
"
= "
+ (values[values.length - 1].equals("") ? "\'
" '\'" : "\'"
+ values[values.length - 1] + "\'");
"
} else {
vals += "" + fields[fields.length - 1] + " = "
+ (values[values.length - 1].equals("") ? "\'
" '\'" : "\'"
+ values[values.length - 1] + "\'");
"
}
return vals;
}
/**
* Converte um vetor de inteiros para um formato aceitável por um campo do
* tipo "array" do PostgreSQL.
*
* @param Vetor de Inteiros
* @return "'{ val1, val2, ... }'"
*/
public String convertToStringArray(int
(int v[]) {
5.1 of 7
String vetor = "";
2013.06.18 16:01:02
Prof. Edwar Saliba Júnior
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
vetor += "{";
for (int i = 0; i < v.length; i++) {
if ((i < (v.length - 1)) && (!((i > 0) &&
(String.valueOf(v[i]).equals("0")))))
(String.
(v[i]).equals("0"))))) {
vetor += String.valueOf(v[i])
String.
(v[i]) + ",";
} else {
vetor += String.valueOf(v[i]);
String.
break;
}
}
vetor += "}";
return (vetor);
}
/**
* Converte um campo do tipo "array" do PostgreSQL (String) num vetor de
* inteiros
s.
*
* @param "String" - Ex.: {0,80,17,71,13,0}
* @return "int []" - Ex.: [0,80,17,71,13,0]
*/
public int[] convertToIntArray(String
(String v) {
v = v.trim();
int vetor[] = new int[v.split(",", -1).length];
int j = 0;
String n = "";
for (int i = 0; i < v.length(); i++) {
if ((v.charAt(i) != '{') && (v.charAt(i) != '}')) {
if ((v.charAt(i) != ',') && (v.charAt(i) != ' ')) {
n += v.substring(i, i + 1);
} else {
vetor[j++] = Integer.parseInt(n);
Integer.
n = "";
}
}
}
return (vetor);
}
public void closeDBConnection()
() throws SQLException {
this.connectionDB.close();
}
public boolean isEnableMessages() {
return enableMessages;
}
public void setEnableMessages(boolean
(boolean enableMessages) {
this.enableMessages = enableMessages;
}
@Override
public void finalize()
() throws SQLException, Throwable {
super.finalize();
closeDBConnection();
}
private Object getFieldValue(String
(String tableName, String fieldName,
String condition) throws SQLException {
boolean putQuotationMarks;
Object value = null;
String fields[] = {fieldName};
/* Se o banco não for PostgreSQL, não colocar
aspas no campo e tampouco na tabela.
*/
putQuotationMarks = (dbms == 1);
ResultSet rs = selection(tableName, fields,
putQuotationMarks, condition, true);
if (rs.first()) {
value = rs.getObject(fieldName);
}
return (value);
}
public String getStringFieldValue(String
(String tables, String fields,
String condition) throws SQLException {
String value = "";
Object val;
6.1 of 7
val = getFieldValue(tables, fields, condition);
if (val != null) {
2013.06.18 16:01:02
Prof.
Edwar
Saliba Júnior
530
if (val != null) {
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591 }
592
value = val.toString();
}
return (value);
}
public int getIntFieldValue(String
(String tables, String fields, String condition)
throws SQLException {
int value = 0;
Object val;
val = getFieldValue(tables, fields, condition);
if (val != null) {
value = Integer.valueOf(val.toString());
Integer.
(val.toString());
}
return (value);
}
public float getFloatFieldValue(String
(String tables, String fields, String condition)
throws SQLException {
float value = 0;
Object val;
val = getFieldValue(tables, fields, condition);
if (val != null) {
value = Float.valueOf
Float.
(val.toString());
}
return (value);
}
public boolean getBooleanFieldValue(String
(String tables, String fields,
String condition) throws SQLException {
boolean value = false;
Object val;
val = getFieldValue(tables, fields, condition);
if (val != null) {
value = Boolean.valueOf(val.toString());
Boolean.
(val.toString());
}
return (value);
}
public int getNumberOfRowsInTable(String
(String table, boolean putQuotation)
throws SQLException {
ResultSet rs;
if (putQuotation) {
rs = selection("SELECT count(*) "
+ " FROM \""
" + table + "\"");
"
} else {
rs = selection("SELECT count(*) "
+ " FROM " + table);
}
int value = rs.getInt(1);
return value;
}
7.1 of 7
2013.06.18 16:01:02