1
|
package io;
|
2
|
|
3
|
import java.sql.Blob;
|
4
|
import java.sql.Connection;
|
5
|
import java.sql.DriverManager;
|
6
|
import java.sql.ResultSet;
|
7
|
import java.sql.SQLException;
|
8
|
import java.sql.Statement;
|
9
|
|
10
|
/**
|
11
|
* https://www.tutorialspoint.com/jdbc/jdbc-db-connections.htm
|
12
|
* https://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm
|
13
|
*/
|
14
|
public class Database {
|
15
|
|
16
|
public static class DB_Messenger {
|
17
|
public String driver;
|
18
|
public String url;
|
19
|
public String user;
|
20
|
public String password;
|
21
|
public String sql;
|
22
|
public String column;
|
23
|
|
24
|
public DB_Messenger(String driver, String url, String user, String password, String table, String condition, String column) {
|
25
|
this.driver = driver;
|
26
|
// The timezone statement added due to MySQL.
|
27
|
//this.url = url + "?useTimezone=true&serverTimezone=UTC";
|
28
|
this.url = url;
|
29
|
this.user = user;
|
30
|
this.password = password;
|
31
|
|
32
|
this.sql = "SELECT " + column + " FROM " + table;
|
33
|
if(condition.length() > 0)
|
34
|
{
|
35
|
this.sql += " WHERE " + condition;
|
36
|
}
|
37
|
this.sql += ";";
|
38
|
|
39
|
this.column = column;
|
40
|
}
|
41
|
|
42
|
@Override
|
43
|
public String toString() {
|
44
|
return "DRIVER: " + driver + "\nURL: " + url + "\nUSER: " + user + "\nPASSWORD: " + password + "\nSQL: " + sql + "\nCOLUMN: " + column;
|
45
|
}
|
46
|
}
|
47
|
|
48
|
public static byte[] getBlobBytes(DB_Messenger crate) {
|
49
|
Connection conn = null;
|
50
|
Statement stmt = null;
|
51
|
byte result[] = null;
|
52
|
|
53
|
try {
|
54
|
|
55
|
Class.forName(crate.driver);
|
56
|
|
57
|
// The second way of the driver registration.
|
58
|
//DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
|
59
|
|
60
|
System.out.println("--- Connecting to the database ---".toUpperCase());
|
61
|
|
62
|
conn = DriverManager.getConnection(crate.url, crate.user, crate.password);
|
63
|
|
64
|
System.out.println("--- Executing the query ---".toUpperCase());
|
65
|
stmt = conn.createStatement();
|
66
|
ResultSet rs = stmt.executeQuery(crate.sql);
|
67
|
|
68
|
while (rs.next()) {
|
69
|
Blob blob = rs.getBlob(crate.column);
|
70
|
if (blob != null && blob.length() > 0) {
|
71
|
result = blob.getBytes(1l, (int) blob.length());
|
72
|
System.out.println("--- The BLOB was found ---".toUpperCase());
|
73
|
break;
|
74
|
}
|
75
|
}
|
76
|
|
77
|
rs.close();
|
78
|
stmt.close();
|
79
|
conn.close();
|
80
|
|
81
|
} catch (SQLException e) {
|
82
|
e.printStackTrace();
|
83
|
} catch (Exception e) {
|
84
|
e.printStackTrace();
|
85
|
} finally {
|
86
|
try {
|
87
|
stmt.close();
|
88
|
} catch (Exception e) {}
|
89
|
try {
|
90
|
conn.close();
|
91
|
} catch (Exception e) {}
|
92
|
}
|
93
|
|
94
|
return result;
|
95
|
}
|
96
|
|
97
|
}
|