Files
Ruokamanageri/src/main/java/fi/lpam/ruokamanageri/dataluokat/Tietokanta.java
T
2026-04-12 20:42:50 +03:00

67 lines
2.1 KiB
Java

package fi.lpam.ruokamanageri.dataluokat;
import fi.lpam.gui.virheDialogit.SiirtoVirhe;
import fi.lpam.Main;
import org.apache.commons.lang3.SystemUtils;
import java.io.*;
import java.sql.*;
import java.util.Objects;
public class Tietokanta {
private static String osoite;
private static String dbPath = SystemUtils.getUserHome().getAbsolutePath() + "\\OneDrive\\Kuljetusruokasovellus\\tietokanta.db";
public Tietokanta(boolean dev) {
if (dev) dbPath = "testikanta.db";
File file = new File(dbPath);
try {
boolean _ = file.getParentFile().mkdirs();
boolean _ = file.createNewFile();
}
catch (Exception _) {}
osoite = "jdbc:sqlite:" + file.getAbsolutePath();
try (Connection conn = haeYhteys()) {
InputStream is = Objects.requireNonNull(Main.class.getClassLoader().getResourceAsStream("tietokanta.sql"));
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String sql = br.readAllAsString();
for (String query : sql.split(";")) {
conn.createStatement().execute(query);
}
}
catch (SQLException | IOException e) {
handleException(e);
}
//Lisää laskutustietokenttä Asiakkaat tauluun
try (Connection conn = haeYhteys()) {
Statement stmt = conn.createStatement();
stmt.execute("alter table asiakkaat add column laskutustieto TEXT");
}
catch (SQLException e) {
if (!e.getMessage().contains("duplicate column name: laskutustieto")) {
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();
}
}