From a1ac8a366bb3f0135de2c48fa8c5aac1ba664308 Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Fri, 3 May 2024 05:29:54 +0200 Subject: [PATCH] Select helper, unsafe but functional --- app/src/main/java/krusty/Database.java | 36 +++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/krusty/Database.java b/app/src/main/java/krusty/Database.java index e673436..6a0dac1 100644 --- a/app/src/main/java/krusty/Database.java +++ b/app/src/main/java/krusty/Database.java @@ -12,6 +12,9 @@ import java.io.BufferedReader; // Likely dependencies for general operations import java.io.IOException; import java.io.FileReader; +import java.sql.ResultSet; +import java.util.StringJoiner; + public class Database { // Here, we use an in-memory database. This string could be changed to @@ -22,7 +25,8 @@ public class Database { private Connection conn = null; public String getCustomers(Request req, Response res) { - return "{}"; + String result = selectQuery("Customers", "customers", "name", "address"); + return result; } public String getRawMaterials(Request req, Response res) { @@ -60,6 +64,36 @@ public class Database { } } + /** + * Selects columns from a table and returns the result as a JSON string. + * Does _absolutely no_ query sanitization, so be careful with user input. + */ + private String selectQuery(String table, String jsonName, String... columns) { + String jsonResult = "{}"; // Valid json to return if fail + + try { + Statement stmt = this.conn.createStatement(); + StringBuilder query = new StringBuilder("SELECT "); + + StringJoiner args = new StringJoiner(", "); + for (String column : columns) { + args.add(column); + } + + query.append(args.toString()); + query.append("\nFROM " + table + ";"); + + /* Sanitization is for cowards */ + + ResultSet result = stmt.executeQuery(query.toString()); + jsonResult = Jsonizer.toJson(result, jsonName); + } catch (SQLException e) { + System.out.printf("Error executing query: \n%s", e); + } + + return jsonResult; + } + // The script location is relative to the gradle // build script ("build.gradle.kts", in this case). /** Reads an sql script into the database */