1
0
Fork 0

Add DB config file support

This commit is contained in:
Ethanell 2020-12-18 11:42:54 +01:00
parent 543376af52
commit c17d02d1f8
3 changed files with 39 additions and 5 deletions

5
.gitignore vendored
View file

@ -34,3 +34,8 @@ out/
##############################
.floo
.flooignore
##############################
## Configuration
##############################
config.json

View file

@ -12,6 +12,7 @@ repositories {
dependencies {
implementation 'org.projectlombok:lombok:1.18.16'
implementation 'org.mariadb.jdbc:mariadb-java-client:2.7.1'
implementation 'com.googlecode.json-simple:json-simple:1.1.1'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
}

View file

@ -3,20 +3,48 @@ package DB;
import Exceptions.NotFoundInTable;
import lombok.Data;
import lombok.Getter;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.*;
public class DB {
static final private String host = "";
static final private String database = "";
static final private String user = "";
static final private String password = "";
@Getter static private Connection connection;
static private JSONObject getAuth() {
try {
File f = new File("./config.json");
if (!f.exists()) {
FileWriter fw = new FileWriter(f);
fw.write(
new JSONObject(
Map.ofEntries(
Map.entry("host", ""),
Map.entry("database", ""),
Map.entry("user", ""),
Map.entry("password", "")
)
).toJSONString()
);
fw.close();
}
return (JSONObject) new JSONParser().parse(new FileReader(f));
} catch (ParseException | IOException e) {
e.printStackTrace();
return null;
}
}
static public boolean connect() {
try {
if (connection == null || connection.isClosed()) {
connection = DriverManager.getConnection("jdbc:mariadb://"+host+"/"+database+"?user="+user+"&password="+password);
JSONObject auth = getAuth();
if (auth != null)
connection = DriverManager.getConnection("jdbc:mariadb://"+auth.get("host")+"/"+auth.get("database")+"?user="+auth.get("user")+"&password="+auth.get("password"));
return true;
}
} catch (SQLException e) {