-
Notifications
You must be signed in to change notification settings - Fork 1
/
MySQLConnection.java
84 lines (71 loc) · 2.49 KB
/
MySQLConnection.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
79
80
81
82
83
84
package edu.whimc.positiontracker.sql;
import com.mysql.cj.jdbc.MysqlConnectionPoolDataSource;
import com.mysql.cj.jdbc.MysqlDataSource;
import com.mysql.cj.x.protobuf.MysqlxPrepare;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import edu.whimc.positiontracker.Tracker;
import org.bukkit.configuration.ConfigurationSection;
/**
* Handles the connection to the SQL database.
*/
public class MySQLConnection {
/** The SQL command to create a table. */
public static final String CREATE_TABLE =
"CREATE TABLE IF NOT EXISTS `whimc_player_positions` (" +
" `rowid` BIGINT AUTO_INCREMENT NOT NULL," +
" `x` INT NOT NULL," +
" `y` INT NOT NULL," +
" `z` INT NOT NULL," +
" `world` VARCHAR(64) NOT NULL," +
" `biome` VARCHAR(64) NOT NULL," +
" `username` VARCHAR(16) NOT NULL," +
" `uuid` VARCHAR(36) NOT NULL," +
" `time` BIGINT NOT NULL," +
" PRIMARY KEY (`rowid`));";
private MysqlDataSource dataSource;
/**
* Constructs a MySQLConnection.
*
* @param plugin The instance of the plugin.
*/
public MySQLConnection(Tracker plugin) {
this.dataSource = new MysqlConnectionPoolDataSource();
ConfigurationSection config = plugin.getConfig();
this.dataSource.setServerName(config.getString("mysql.host", "localhost"));
this.dataSource.setPortNumber(config.getInt("mysql.port", 3306));
this.dataSource.setDatabaseName(config.getString("mysql.database", "minecraft"));
this.dataSource.setUser(config.getString("mysql.username", "user"));
this.dataSource.setPassword(config.getString("mysql.password", "pass"));
}
/**
* Attempt to connect to the database and create/update the schema.
*
* @return Whether the database was successfully initialized.
*/
public boolean initialize() {
try (Connection connection = getConnection()) {
if (connection == null) {
return false;
}
try (PreparedStatement statement = connection.prepareStatement(CREATE_TABLE)) {
statement.execute();
}
} catch (SQLException unused) {
return false;
}
return true;
}
/**
* A connection to the configured database or null if unsuccessful.
*/
public Connection getConnection() throws SQLException {
Connection connection = this.dataSource.getConnection();
if (!connection.isValid(1)) {
return null;
}
return connection;
}
}