Files
Ruokamanageri/src/main/java/fi/lpam/ruokamanageri/dataluokat/Tietokanta.java
T
2026-05-08 16:38:43 +03:00

69 lines
2.2 KiB
Java

package fi.lpam.ruokamanageri.dataluokat;
import fi.lpam.ruokamanageri.gui.virheDialogit.SiirtoVirhe;
import fi.lpam.ruokamanageri.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ää kuljetuspäivät asiakassarakkeeseen (v2.0.2->3.x.x)
String[] sarakkeet = {"lauantaiKpl", "sunnuntaiKpl"};
for (String sarake : sarakkeet) {
try (Connection conn = haeYhteys()) {
PreparedStatement stmt = conn.prepareStatement("alter table asiakkaat add column " + sarake + " int not null default 0");
stmt.execute();
} 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();
}
}