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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
package com.redstoner.misc.mysql.elements;
import com.redstoner.misc.mysql.MysqlHandler;
import com.redstoner.misc.mysql.MysqlQueryHandler;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class MysqlDatabase {
private Connection connection = null;
private final MysqlHandler handler;
private final String databaseName;
public MysqlDatabase(MysqlHandler handler, String databaseName) {
this.handler = handler;
this.databaseName = databaseName;
}
public MysqlTable getTable(String name) {
return new MysqlTable(this, name);
}
public boolean createTable(String name, MysqlField... description) {
return MysqlQueryHandler.queryNoResult(getConnection(), "CREATE TABLE `" + name + "` " + getDescription(description) + ";");
}
private String getDescription(MysqlField... description) {
String desc = "(";
for (int i = 0; i < description.length; i++) {
String nil = "";
if (description[i].canBeNull()) {
nil = " NOT NULL";
}
desc += "`" + description[i].getName() + "` " + description[i].getType().getName() + nil;
if (i < description.length - 1) {
desc += ",";
}
}
desc += ")";
return desc;
}
public boolean createTableIfNotExists(String name, MysqlField... description) {
return MysqlQueryHandler.queryNoResult(getConnection(), "CREATE TABLE IF NOT EXISTS `" + name + "` " + getDescription(description) + ";");
}
public boolean dropTable(String name) {
return MysqlQueryHandler.queryNoResult(getConnection(), "DROP TABLE `" + name + "`;");
}
public boolean drop() {
return MysqlQueryHandler.queryNoResult(getConnection(), "DROP DATABASE `" + getName() + "`;");
}
public String getName() {
try {
return getConnection().getCatalog();
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public List<MysqlTable> getTables() {
try {
List<MysqlTable> tables = new ArrayList<>();
DatabaseMetaData metadata = getConnection().getMetaData();
ResultSet queryResults = metadata.getTables(null, null, "%", null);
while (queryResults.next()) {
tables.add(new MysqlTable(this, queryResults.getString(3)));
}
return tables;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
Connection getConnection() {
try {
if (connection == null || connection.isClosed()) {
connection = handler.getConnection(databaseName);
}
} catch (SQLException e) {
e.printStackTrace();
connection = handler.getConnection(databaseName);
}
return connection;
}
}
|