forked from vbarhate/OSAandSAST
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMySqlClient.java
78 lines (63 loc) · 2.12 KB
/
MySqlClient.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.cx.automation.adk.database;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
/**
* Created by: iland
* Date: 7/1/2015
*/
public class MySqlClient {
private static final Logger log = LoggerFactory.getLogger(MySqlClient.class);
private static final int DEFAULT_PORT = 3306;
public Connection conn;
private String host;
private Integer port;
private String user;
private String password;
private String dbName;
public MySqlClient(String host, Integer port, String user, String password, String dbName) {
this.host = host;
this.port = port != null ? port : DEFAULT_PORT;
this.user = user;
this.password = password;
this.dbName = dbName;
connect();
}
private Connection connect() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + dbName, user, password);
log.info("Connected to the database");
return conn;
} catch (Exception e) {
log.error("Fail to connect.", e);
return null;
}
}
public void disconnect() {
try {
conn.close();
log.info("Disconnected from database");
} catch (SQLException e) {
log.error("Fail to disconnect.", e);
}
}
public ResultSet executeQuery(String sql) {
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
return preparedStatement.executeQuery();
} catch (SQLException e) {
log.error("Query failed to execute.", e);
return null;
}
}
public Integer executeUpdate(String sql) {
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
return preparedStatement.executeUpdate();
} catch (SQLException e) {
log.error("Query failed to execute.", e);
return null;
}
}
}