Projekt

Obecné

Profil

Stáhnout (2.36 KB) Statistiky
| Větev: | Tag: | Revize:
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 DB. Is it OK with MsSQL and Oracle?
27
			this.url = url + "?useTimezone=true&serverTimezone=UTC";
28
			this.user = user;
29
			this.password = password;
30

    
31
			this.sql = "SELECT " + column + " FROM " + table;
32
			if(condition.length() > 0)
33
			{
34
				this.sql += " WHERE " + condition;
35
			}
36
			this.sql += ";";
37

    
38
			this.column = column;
39
		}
40
		
41
		@Override
42
		public String toString() {
43
			return "DRIVER: " + driver + "\nURL: " + url + "\nUSER: " + user + "\nPASSWORD: " + password + "\nSQL: " + sql + "\nCOLUMN: " + column;
44
		}
45
	}
46

    
47
	public static byte[] getBlobBytes(DB_Messenger crate) {
48
		Connection conn = null;
49
		Statement stmt = null;
50
		byte result[] = null;
51

    
52
		try {
53
			
54
			Class.forName(crate.driver);
55
			
56
			// The second way of the driver registration.
57
			//DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
58

    
59
			System.out.println("--- Connecting to the database ---".toUpperCase());
60

    
61
			conn = DriverManager.getConnection(crate.url, crate.user, crate.password);
62

    
63
			System.out.println("--- Executing the query ---".toUpperCase());
64
			stmt = conn.createStatement();
65
			ResultSet rs = stmt.executeQuery(crate.sql);
66

    
67
			while (rs.next()) {
68
				Blob blob = rs.getBlob(crate.column);
69
				if (blob != null && blob.length() > 0) {
70
					result = blob.getBytes(1l, (int) blob.length());
71
					System.out.println("--- The BLOB was found ---".toUpperCase());
72
					break;
73
				}
74
			}
75

    
76
			rs.close();
77
			stmt.close();
78
			conn.close();
79
			
80
		} catch (SQLException e) {
81
			e.printStackTrace();
82
		} catch (Exception e) {
83
			e.printStackTrace();
84
		} finally {
85
			try {
86
				stmt.close();
87
			} catch (Exception e) {}
88
			try {
89
				conn.close();
90
			} catch (Exception e) {}
91
		}
92
		
93
		return result;
94
	}
95
	
96
}
(1-1/5)