1
0
Fork 0

Add DB create function

This commit is contained in:
Ethanell 2020-12-18 11:43:26 +01:00
parent c17d02d1f8
commit ffa8c80e22
3 changed files with 49 additions and 2 deletions

View file

@ -1,5 +1,6 @@
package DB;
import Exceptions.AlreadyOnTable;
import Exceptions.NotFoundInTable;
import lombok.Data;
import lombok.Getter;
@ -146,6 +147,32 @@ public class DB {
}
}
static public <T> T create(Class<T> cl, String table, String id, Map<String, String> values) throws AlreadyOnTable {
try {
if (exist(table, id, values.get(id)))
throw new AlreadyOnTable(values.get(id));
String query = String.format(
"INSERT INTO "+table+" (%s) VALUES (%s)",
String.join(",", values.keySet()),
String.join(",", Collections.nCopies(values.values().size(), "?"))
);
PreparedStatement ps = DB.connection.prepareStatement(query);
int i = 1;
for (String value : values.values()) {
ps.setString(i, value);
i++;
}
int r = ps.executeUpdate();
ps.close();
if (r > 0)
return cl.getConstructor(String.class).newInstance(values.get(id));
} catch (SQLException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
System.out.println(e);
return null;
}
return null;
}
static public boolean delete(String table, String check, String checkValue) {
try {
PreparedStatement ps = DB.connection.prepareStatement("DELETE FROM "+table+" WHERE "+check+" = ?");

View file

@ -0,0 +1,5 @@
package Exceptions;public class AlreadyOnTable extends Exception {
public AlreadyOnTable(String name) {
super(name+" is already on the table");
}
}

View file

@ -1,12 +1,27 @@
package ProjectionPlanning;
import DB.*;
import Exceptions.AlreadyOnTable;
import Exceptions.NotFoundInTable;
import java.util.Collections;
import java.util.Map;
public class Main {
public static void main(String[] args) throws NotFoundInTable {
public static void main(String[] args) throws AlreadyOnTable {
//new GUI();
DB.connect();
System.out.println(new User("test@test.com").exist());
User u = DB.create(User.class,
"User",
"email",
Map.ofEntries(
Map.entry("email", "test2@test.com"),
Map.entry("firstName", "Test2"),
Map.entry("lastName", "Test2"),
Map.entry("phoneNumber", "0000000000")
)
);
System.out.println(u);
System.out.println(u.getFirstName());
}
}