public void createDump() {
try (var con = getConnection(); //
var s = con.createStatement(); //
var rset = s.executeQuery("SHOW TABLES")) {
final var fileName = database + "_dump_" + DATE_TIME_FORMATTER.format(LocalDateTime.now()) + ".sql";
var dump = new File("dumps", fileName);
new File("dumps").mkdir();
dump.createNewFile();
if (rset.last()) {
rset.beforeFirst();
}
try (var fileWriter = new FileWriter(dump);
var fws = new FileWriterStdout(fileWriter)) {
while (rset.next()) {
fws.println("CREATE TABLE `" + rset.getString(1) + "`");
fws.println("(");
try (var desc = con.createStatement();
var dset = desc.executeQuery("DESC " + rset.getString(1))) {
final var keys = new HashMap<String, List<String>>();
var isFirst = true;
while (dset.next()) {
if (!isFirst) {
fws.println(",");
}
fws.print("\t`" + dset.getString(1) + "`");
fws.print(" " + dset.getString(2));
if (dset.getString(3).equals("NO")) {
fws.print(" NOT NULL");
}
if (!dset.getString(4).isEmpty()) {
if (!keys.containsKey(dset.getString(4))) {
keys.put(dset.getString(4), new ArrayList<String>());
}
keys.get(dset.getString(4)).add(dset.getString(1));
}
if (dset.getString(5) != null) {
fws.print(" DEFAULT '" + dset.getString(5) + "'");
}
if (!dset.getString(6).isEmpty()) {
fws.print(" " + dset.getString(6));
}
isFirst = false;
}
if (keys.containsKey("PRI")) {
fws.println(",");
fws.print("\tPRIMARY KEY (");
isFirst = true;
for (String key : keys.get("PRI")) {
if (!isFirst) {
fws.print(", ");
}
fws.print("`" + key + "`");
isFirst = false;
}
fws.print(")");
}
if (keys.containsKey("MUL")) {
fws.println(",");
isFirst = true;
for (String key : keys.get("MUL")) {
if (!isFirst) {
fws.println(", ");
}
fws.print("\tKEY `key_" + key + "` (`" + key + "`)");
isFirst = false;
}
}
fws.println();
fws.println(");");
fws.flush();
}
try (var desc = con.createStatement();
var dset = desc.executeQuery("SELECT * FROM " + rset.getString(1))) {
boolean isFirst = true;
int cnt = 0;
while (dset.next()) {
if ((cnt % 100) == 0) {
fws.println("INSERT INTO `" + rset.getString(1) + "` VALUES ");
} else {
fws.println(",");
}
fws.print("\t(");
boolean isInFirst = true;
for (int i = 1; i <= dset.getMetaData().getColumnCount(); i++) {
if (!isInFirst) {
fws.print(", ");
}
if (dset.getString(i) == null) {
fws.print("NULL");
} else {
fws.print("'" + dset.getString(i).replace("\'", "\\\'") + "'");
}
isInFirst = false;
}
fws.print(")");
isFirst = false;
if ((cnt % 100) == 99) {
fws.println(";");
}
cnt++;
}
if (!isFirst && ((cnt % 100) != 0)) {
fws.println(";");
}
fws.println();
fws.flush();
}
}
fws.flush();
}
} catch (Exception ex) {
System.err.println("There has been an error creating a database backup for " + database + "!");
ex.printStackTrace();
}
}