diff --git a/src/main/java/krusty/Database.java b/src/main/java/krusty/Database.java index 4e7ac55..978dcb2 100644 --- a/src/main/java/krusty/Database.java +++ b/src/main/java/krusty/Database.java @@ -6,6 +6,7 @@ import spark.Response; import java.util.Arrays; import java.util.Map; import java.util.TreeMap; +import java.sql.*; import static krusty.Jsonizer.toJson; @@ -13,20 +14,41 @@ public class Database { /** * Modify it to fit your environment and then use this string when connecting to your database! */ - private static final String jdbcString = "jdbc:mysql://localhost/krusty"; + private static final String jdbcString = "jdbc:mysql://pusp.cs.lth.se:3306/iv4171bo"; // For use with MySQL or PostgreSQL - private static final String jdbcUsername = ""; - private static final String jdbcPassword = ""; + private static final String jdbcUsername = "iv4171bo"; + private static final String jdbcPassword = "i2qtnm8z"; + + private Connection conn; public void connect() { // Connect to database here + try { + // Connection strings for included DBMS clients: + // [MySQL] jdbc:mysql://[host]/[database] + // [PostgreSQL] jdbc:postgresql://[host]/[database] + // [SQLite] jdbc:sqlite://[filepath] + + // Use "jdbc:mysql://puccini.cs.lth.se/" + userName if you using our shared server + // If outside, this statement will hang until timeout. + conn = DriverManager.getConnection + (jdbcString, jdbcUsername, jdbcPassword); + } + catch (SQLException e) { + System.err.println(e); + e.printStackTrace(); + } } // TODO: Implement and change output in all methods below! public String getCustomers(Request req, Response res) { - return "{}"; + String query = "SELECT name, address FROM Customer"; + String title = "Customer"; + + return getJson(query, title); + } public String getRawMaterials(Request req, Response res) { @@ -52,4 +74,15 @@ public class Database { public String createPallet(Request req, Response res) { return "{}"; } + + private String getJson(String query, String title) { //privat hjälpmetod så man slipper kalla på jsonizer varje gång + try { + PreparedStatement stmt = conn.prepareStatement(query); + ResultSet rs = stmt.executeQuery(); + + return Jsonizer.toJson(rs, title); + } catch (SQLException e) { + return ""; + } + } }