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
|
public class Database {
|
11
|
|
12
|
private static class DB_Messenger {
|
13
|
public String url; // jdbc:mysql://localhost/mydb
|
14
|
public String user; // root
|
15
|
public String password; // 1234
|
16
|
public String query; // SELECT * FROM table
|
17
|
public String blob; // image
|
18
|
|
19
|
public DB_Messenger(String url, String user, String password, String query, String blob) {
|
20
|
this.url = url;
|
21
|
this.user = user;
|
22
|
this.password = password;
|
23
|
this.query = query;
|
24
|
this.blob = blob;
|
25
|
}
|
26
|
}
|
27
|
|
28
|
public byte[] doWork(DB_Messenger crate) {
|
29
|
Connection conn = null;
|
30
|
Statement stmt = null;
|
31
|
|
32
|
try {
|
33
|
System.out.println("Connecting to the database...");
|
34
|
conn = DriverManager.getConnection(crate.url, crate.user, crate.password);
|
35
|
System.out.println("Connected.");
|
36
|
} catch (SQLException e) {
|
37
|
System.out.println("Connection error.");
|
38
|
e.printStackTrace();
|
39
|
return null;
|
40
|
}
|
41
|
|
42
|
System.out.println("Getting the BLOB...");
|
43
|
try {
|
44
|
stmt = conn.createStatement();
|
45
|
ResultSet rs = stmt.executeQuery(crate.query);
|
46
|
while (rs.next()) {
|
47
|
Blob blob = rs.getBlob(crate.blob);
|
48
|
if (blob != null) {
|
49
|
byte[] bytes = blob.getBytes(1l, (int) blob.length());
|
50
|
System.out.println("The BLOB was found.");
|
51
|
return bytes;
|
52
|
}
|
53
|
}
|
54
|
} catch (SQLException e) {
|
55
|
System.out.println("Error getting the BLOB.");
|
56
|
e.printStackTrace();
|
57
|
|
58
|
}
|
59
|
|
60
|
System.out.println("The BLOB wasn't found.");
|
61
|
return null;
|
62
|
}
|
63
|
|
64
|
}
|