Select helper, unsafe but functional
This commit is contained in:
parent
87ba5bb679
commit
a1ac8a366b
1 changed files with 35 additions and 1 deletions
|
@ -12,6 +12,9 @@ import java.io.BufferedReader;
|
||||||
// Likely dependencies for general operations
|
// Likely dependencies for general operations
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.FileReader;
|
import java.io.FileReader;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.util.StringJoiner;
|
||||||
|
|
||||||
|
|
||||||
public class Database {
|
public class Database {
|
||||||
// Here, we use an in-memory database. This string could be changed to
|
// Here, we use an in-memory database. This string could be changed to
|
||||||
|
@ -22,7 +25,8 @@ public class Database {
|
||||||
private Connection conn = null;
|
private Connection conn = null;
|
||||||
|
|
||||||
public String getCustomers(Request req, Response res) {
|
public String getCustomers(Request req, Response res) {
|
||||||
return "{}";
|
String result = selectQuery("Customers", "customers", "name", "address");
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getRawMaterials(Request req, Response res) {
|
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
|
// The script location is relative to the gradle
|
||||||
// build script ("build.gradle.kts", in this case).
|
// build script ("build.gradle.kts", in this case).
|
||||||
/** Reads an sql script into the database */
|
/** Reads an sql script into the database */
|
||||||
|
|
Loading…
Reference in a new issue