This question is to do with generating a preparedstatement from a hash of strings and dealing with some strings that are Date, Times and Int.
I have a Database, the column names of this database are stored in list "columns".
I also have a hashmap "pdf" which stores fieldnames and values from a PDF document.
The code below looks for a matching column name from the DB against the pdf hashmap and if found inserts it.
StringJoiner col = new StringJoiner(",");
StringJoiner val = new StringJoiner(",");
//First Iteration: Create the Statement
for(String c : columns) {
//Your PDF has a matching formfield
if(pdf.hasKey(c)) {
col.add(c);
val.add("?");
}
}
String sql = String.format("INSERT INTO table (%s) VALUES (%s)", col.toString(), val.toString());
try(PreparedStatement insert = con.prepareStatement(sql)) {
//Insert position in statement
int pos = 0;
//Second iterations: Bind the values to the statement
for(String c : columns) {
//Your PDF has a matching formfield
if(pdf.hasKey(c)) {
insert.setString(++pos, pdf.get(c));
}
}
insert.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
This works well, but I need to handle a few cases. The pdf has the following fields which are Int and Date, Time:
Age (Int) DOB (Date) Score (Int) DateStart (Date) TimeStart (Time)
I also want to modify the DB to just have a single DateTimeStart field which will hold both.
Now I did have a go at handling this with something like:
if (c.toLowerCase().contains("date")) {
System.out.println("A Date field has been found: " +c);
DateTimeFormatter formatter = DateTimeFormat.forPattern ("dd/mm/yyyy");
DateTime startdt = formatter.parseDateTime(pdf.get(c));
insert.setDate(++pos, startdt);
}
if (pdf.containsKey(c) && !c.toLowerCase().contains("date")) {
insert.setString(++pos, pdf.get(c));
}
But this doesnt work. For starters setDate doesnt accept DateTime objects, even if they only contain a date. Also trying to get my head around the new prepared statement with the database now only containing "DateTimeStart" instead of "DateStart" and "TimeStart" gave me a headache.
Any help here would be appreciated. I am already using Joda since its Java7.
Cheers
-Al
if (c.toLowerCase().contains("date")) {
System.out.println("A Date field has been found: " +c);
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/mm/yyyy kk:mm");
long millis = formatter.parseMillis(pdf.get("DateStart") +" " +pdf.get("TimeStart"));
Timestamp timeStamp = new Timestamp(millis);
insert.setTimestamp(++pos, timeStamp);
}