Projekt

Obecné

Profil

Stáhnout (2.17 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
			this.url = url;
27
			this.user = user;
28
			this.password = password;
29
			this.sql = "SELECT " + column + " FROM " + table + " WHERE " + condition + ";";
30
			this.column = column;
31
		}
32
		
33
		@Override
34
		public String toString() {
35
			return "DRIVER: " + driver + "\nURL: " + url + "\nUSER: " + user + "\nPASSWORD: " + password + "\nSQL: " + sql + "\nCOLUMN: " + column;
36
		}
37
	}
38

    
39
	public static byte[] getBlobBytes(DB_Messenger crate) {
40
		Connection conn = null;
41
		Statement stmt = null;
42
		byte result[] = null;
43

    
44
		try {
45
			
46
			Class.forName(crate.driver);
47
			
48
			// The second way of the driver registration.
49
			//DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
50

    
51
			System.out.println("--- Connecting to the database ---".toUpperCase());
52
			conn = DriverManager.getConnection(crate.url, crate.user, crate.password);
53

    
54
			System.out.println("--- Executing the query ---".toUpperCase());
55
			stmt = conn.createStatement();
56
			ResultSet rs = stmt.executeQuery(crate.sql);
57

    
58
			while (rs.next()) {
59
				Blob blob = rs.getBlob(crate.column);
60
				if (blob != null && blob.length() > 0) {
61
					result = blob.getBytes(1l, (int) blob.length());
62
					System.out.println("--- The BLOB was found ---".toUpperCase());
63
					break;
64
				}
65
			}
66

    
67
			rs.close();
68
			stmt.close();
69
			conn.close();
70
			
71
		} catch (SQLException e) {
72
			e.printStackTrace();
73
		} catch (Exception e) {
74
			e.printStackTrace();
75
		} finally {
76
			try {
77
				stmt.close();
78
			} catch (Exception e) {}
79
			try {
80
				conn.close();
81
			} catch (Exception e) {}
82
		}
83
		
84
		return result;
85
	}
86
	
87
}
(1-1/5)