Files
Ruokamanageri/src/main/java/fi/lpam/dataluokat/Tietokanta.java
T

62 lines
1.9 KiB
Java

package fi.lpam.dataluokat;
import fi.lpam.gui.virheDialogit.SiirtoVirhe;
import fi.lpam.Main;
import org.apache.commons.lang3.SystemUtils;
import java.io.*;
import java.nio.file.Path;
import java.sql.*;
import java.util.Objects;
public class Tietokanta {
private static String osoite;
private static File tietokantatiedosto = Path.of(SystemUtils.getUserHome().getAbsolutePath(), "OneDrive", "Kuljetusruokasovellus", "tietokanta.db").toFile();
public Tietokanta(boolean dev) {
if (dev) tietokantatiedosto = new File("testikanta.db");
try {
boolean _ = tietokantatiedosto.getParentFile().mkdirs();
boolean _ = tietokantatiedosto.createNewFile();
}
catch (Exception _) {}
osoite = "jdbc:sqlite:" + tietokantatiedosto.getAbsolutePath();
String sql = "";
try (BufferedReader br = new BufferedReader(
new InputStreamReader(
Objects.requireNonNull(Main.class.getClassLoader()
.getResourceAsStream("tietokanta.sql"))))) {
sql = br.readAllAsString();
} catch (IOException e) {
throw new RuntimeException(e);
}
for (String query : sql.split(";")) {
try (Connection conn = haeYhteys()) {
conn.createStatement().execute(query);
} catch (SQLException e) {
if (!e.getMessage().contains("duplicate column name")) {
handleException(e);
}
}
}
}
public static Connection haeYhteys() {
Connection connection = null;
try {
connection = DriverManager.getConnection(osoite);
} catch (SQLException e) {
handleException(e);
}
return connection;
}
private static void handleException(Exception e) {
SiirtoVirhe virhe = new SiirtoVirhe(e);
virhe.showAndWait();
}
}