NounsPicker/src/main/java/wtf/beatrice/nounspicker/utils/DatabaseManager.java
Beatrice DellacĂ  e7e57506c4
Some checks failed
continuous-integration/drone/push Build is failing
Start implementing add command
2022-10-24 20:35:57 +02:00

135 lines
3.5 KiB
Java

package wtf.beatrice.nounspicker.utils;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DatabaseManager
{
private final static String sqliteURL = "jdbc:sqlite:%path%";
private Connection dbConnection = null;
private ConsoleLogger logger;
private final String dbPath;
public DatabaseManager(String dbPath)
{
this.dbPath = dbPath;
logger = new ConsoleLogger(getClass());
}
public boolean connect()
{
String url = sqliteURL.replace("%path%", dbPath);
if(!close()) return false;
try {
dbConnection = DriverManager.getConnection(url);
logger.log("Database connection established!");
return true;
} catch (SQLException e) {
logger.err(e.getMessage());
return false;
}
}
public boolean close()
{
if (dbConnection != null)
{
try {
if(!dbConnection.isClosed())
{
dbConnection.close();
}
} catch (SQLException e) {
logger.err(e.getMessage());
return false;
}
dbConnection = null;
}
return true;
}
public boolean initDb()
{
List<String> newTables = new ArrayList<>();
newTables.add("CREATE TABLE IF NOT EXISTS players (" +
"player text NOT NULL," +
"main_pronoun_id integer," +
"secondary_pronoun_id integer" +
");");
newTables.add("CREATE TABLE IF NOT EXISTS pronouns (" +
"pronoun text," +
"format text," +
"\"id integer" +
");");
for(String sql : newTables)
{
try (Statement stmt = dbConnection.createStatement()) {
// execute the statement
stmt.execute(sql);
} catch (SQLException e) {
logger.err(e.getMessage());
return false;
}
}
return true;
}
/**
* DB STRUCTURE
* TABLE 1: PLAYERS
* -----------------------------------------------------------------
* | name | main_pronoun_id | secondary_pronoun_id |
* -----------------------------------------------------------------
* | AstroBea | 1 | 2 |
* | Notch | 3 | 1 |
* -----------------------------------------------------------------
*
*
* TABLE 2: PRONOUNS
* --------------------------------------
* | pronoun | id | format |
* --------------------------------------
* | she | 1 | She |
* | her | 2 | Her |
* | he | 3 | He |
* -------------------------------------
*
*/
public int getPronounId(String pronoun) {
String query = "SELECT id " +
"FROM pronouns " +
"WHERE pronoun = ?;";
try (PreparedStatement pStatement = dbConnection.prepareStatement(query)) {
pStatement.setString(1, pronoun);
ResultSet resultSet = pStatement.executeQuery();
while(resultSet.next())
{
return resultSet.getInt("id");
}
} catch (SQLException e)
{
logger.err(e.getMessage());
}
return -1;
}
}