How to convert a JTextField String to java.sql.date Date - sql

A frequently asked question (also for me) was: How to convert a simple String from e.g. a JTextField to a java.sql.date Date - to insert some GUI-User-Input as correctly formatted Date into a table through a Prepared Statement.

I'd write a new convert-specified Class, which has this option.
import java.text.SimpleDateFormat;
import java.util.Date;
public class convertText {
public java.sql.Date formatStringToSQLDate(String strDate) throws Exception{
Date utilDate = new Date(); //DateFormat
SimpleDateFormat dfFormat = new SimpleDateFormat("dd.MM.yyyy"); // parse string into a DATE format
utilDate = dfFormat.parse(strDate); // convert a util.Date to milliseconds via its getTime() method
long time = utilDate.getTime(); // get the long value of java.sql.Date
java.sql.Date sqlDate = new java.sql.Date(time);
return sqlDate;
}
}
Afterwards, to use it like this.
Connection dp = DriverManager.getConnection("jdbc:ucanaccess://" + Filepath + Filename);
Statement stat = dp.createStatement();
String sql = "INSERT INTO user_table (Name, Birth) VALUES(?, ?)"; //statement as string
PreparedStatement pstmt = dp.prepareStatement(sql);
pstmt.setString(1, textFieldVorname.getText()); //replaces the first '?'
pstmt.setDate(2, Date.formatStringToSQLDate(textFieldGeburtsdatum.getText())); //replaces the second '?'
pstmt.executeUpdate(); //executes the insert-query

Related

Getting error: failed to convert parameter value from a String to a DateTime

I get this error:
Failed to convert parameter value from a String to a DateTime.
The error occurs at ExecuteDataset(Connection, cmd, query, parameters);
Code:
int paramCount = 2 + results.Count;
SqlParameter[] sqlParam = new SqlParameter[2];
sqlParam[0] = new SqlParameter("#FROMDATE", SqlDbType.DateTime);
sqlParam[0].Value = Convert.ToDateTime(SearchRequest.FromDate).ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
results.Add(sqlParam[0]);
sqlParam[1] = new SqlParameter("#TODATE", SqlDbType.DateTime);
sqlParam[1].Value = Convert.ToDateTime(SearchRequest.ToDate).ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
results.Add(sqlParam[1]);
foreach (var o in strCode)
{
SqlParameter paramRef = new SqlParameter();
paramRef.ParameterName = "#Param" + results.Count;
paramRef.Value = o;
results.Add(paramRef);
lstParam.Add(paramRef.ParameterName);
}
SqlParameter[] sqlParams = new SqlParameter[paramCount];
sqlParams = results.ToArray();
string Query;
Query = "select StudID,StudName from StudentDetails
where CourseCode in ({2}) and Coursedate between #FROMDATE and #TODATE";
var inClause = String.Join(",", lstParam);
Query = Query.Replace("{2}", inClause);
Issue is resolved, I was passing incorrect date format...
During debugging DATE do read it as e.g 20130831 which I changed it to 2013-08-31 format and it worked for me...

Why is my LocalDateTime variable changing by 5 hours when I get from my sql to my spring-boot application?

My LocalDateTime variable changes by 5 hours every time I get it by querying my sql table. If I have a time that starts at 9:30am then it'll return 4:30am as the time.
Whenever I try to get a datetime type field from my sql table by querying it in my repo
#Query(value = "SELECT start FROM course_section WHERE crn = ?1", nativeQuery = true)
LocalDateTime getStartTimeByCrn(int term);
#Query(value = "SELECT end FROM course_section WHERE crn = ?1", nativeQuery = true)
LocalDateTime getEndTimeByCrn(int term);
I send it to my service
//Method to get the Start time for Section class
public LocalDateTime getStartTimeByCrn(int term) {
LocalDateTime start = (LocalDateTime) repo.getStartTimeByCrn(term);
return start;
}
//Method to get the End time for the Section class
public LocalDateTime getEndTimeByCrn(int term) {
LocalDateTime end = (LocalDateTime) repo.getEndTimeByCrn(term);
return end;
and my controller uses the methods
#RequestMapping(value = "/accepted", method = RequestMethod.POST)
public String addSchedule(#ModelAttribute("schedule") Schedule schedule) throws JsonProcessingException {
int crn = schedule.getCrn();
Section sec = new Section();
//set all the attributes of Section object
sec.setStart(service.getStartTimeByCrn(crn));
sec.setEnd(service.getEndTimeByCrn(crn));
// String stringToJson = new JsonMapper().writeValueAsString(sec);
service.save(sec);
System.out.print( sec.getStart() + " is the subject!!!");
return "calendar";
}
My datetime variable in a row will change by five hours when I get it by the crn from my sql table. Nothing else is changed, not the year, month, day, min, or sec.
My #Entity LocalDateTime variables look like
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss")
private LocalDateTime start;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss")
private LocalDateTime end;
There seems like there is no logical reason for this bug to happen...

Insert line breaks in VariableReplace in docx4j

I have been trying to fill up a word template(.docx) file which has placeholders which needs to be replaced.
I was able to rewrite the template but the text does not come with line breaks
I understand that carriage return or new line (\r\n) does not work in .docx files. I used the VariableReplace method to convert but I was unable to place br or factory.createBr() while using the variable replace.
Any suggestions would be really helpful. Below is the piece of code what i tried
Map<String,String> variableReplaceMap = new HashMap<>();
Map<String, String> textContent = readTextContentAfterDBExtractionToFillUpTemplate();
ObjectFactory factory = Context.getWmlObjectFactory();
P para = factory.createP();
R rspc = factory.createR();
String power= textContent.get("Power & Energy");
String[] powerWithNewLine = skills.split("\\\\n");
for (String eachLineOfPower : powerWithNewLine) {
Text eachLineOfPowerTxt = factory.createText();
eachLineOfPowerTxt .setValue( eachLineOfPower );
rspc.getContent().add( eachLineOfPowerTxt );
Br br = factory.createBr();
rspc.getContent().add(br);
para.getParagraphContent().add(rspc);
documentPart.addObject(para);
}
String str = "";
for (Object eachLineOfPgrph : para.getParagraphContent()) {
str = str + eachLineOfPgrph;
}
variableReplaceMap.put("POWER", str);
return variableReplaceMap;
The link from Jason is dead.
Here is the current link: https://github.com/plutext/docx4j/blob/master/docx4j-samples-docx4j/src/main/java/org/docx4j/samples/VariableReplace.java
In case it gets changed in the future, simply use the following function and apply it to your string, that contains linebreaks:
/**
* Hack to convert a new line character into w:br.
* If you need this sort of thing, consider using
* OpenDoPE content control data binding instead.
*
* #param r
* #return
*/
private static String newlineToBreakHack(String r) {
StringTokenizer st = new StringTokenizer(r, "\n\r\f"); // tokenize on the newline character, the carriage-return character, and the form-feed character
StringBuilder sb = new StringBuilder();
boolean firsttoken = true;
while (st.hasMoreTokens()) {
String line = (String) st.nextToken();
if (firsttoken) {
firsttoken = false;
} else {
sb.append("</w:t><w:br/><w:t>");
}
sb.append(line);
}
return sb.toString();
}
See newlineToBreakHack method at https://github.com/plutext/docx4j/blob/master/src/samples/docx4j/org/docx4j/samples/VariableReplace.java#L122

Dapper: String is passed on as Text when invoking postgres functions

When calling a DB function in Postgres, the type for String changes to text and that of DateTime to timestamp. Is there any way to ensure this doesn't happen?
Setup:
a DB function:
foo(v_from character varying, v_to character varying, v_date date)
Dapper code:
public static decimal GetValue(DateTime vdate, string cur) {
string sql = #"SELECT _public.foo(#vFrom, #vTo, #vDate)";
var data = connection.QueryFirstOrDefault<decimal>(
sql,
new
{
vFrom = cur,
vTo = cur,
vDate = valdate,
}
);
}
I receive the following error:
Npgsql.PostgresException : 42883: Function _public.foo(text, text, timestamp without time zone) does not exist
Somehow string is converted to text instead of character varchar. Similar story for DateTime to timestamp.
Tried the variation with DynamicParameters.Add(), but still the same result.
Try this?
public static decimal GetValue(DateTime vdate, string cur) {
string sql = #"SELECT _public.foo(#vFrom::character varying, #vTo::character varying, #vDate::date)";
var data = connection.QueryFirstOrDefault<decimal>(
sql,
new
{
vFrom = cur,
vTo = cur,
vDate = valdate,
}
);
}

Can anyone see why this SQL insert will not work? (Exception to String and Date to String Inserted) - JDBC

Im trying to basically make a log of errors generated from a Java program and save them in an SQL table with 2 colums( Error and Date )
Try and catch sends the error to the method which should hopefully insert into database but its failing somewhere. Im new enough to Java so im not sure how to debug it properly or get more details on wahts going wrong and where
Heres the method.
public void createErrorLog(Exception error) throws SQLException{
// Error as String
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
error.printStackTrace(pw);
sw.toString(); // stack trace as a string
String errorOne = sw.toString();
System.out.println(errorOne);
// Date
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
String dateString = dateFormat.format(date);
Connection conn = null;
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected to database.");
String insertSaleProperty = "INSERT INTO ErrorLogs"
+ "(Error, "
+ "Time, "
+ "(?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(insertSaleProperty);
preparedStatement.setString(1, errorOne);
preparedStatement.setString(2, dateString);
// execute insert SQL statement
preparedStatement.executeUpdate();
} catch (SQLException e) {
System.err.println("Cannot write to database.");
} finally {
if(conn != null){
conn.close();
}
}
}
Try the following.
String insertSaleProperty = "INSERT INTO ErrorLogs"
+ "(Error,Time) values "
+ "(?,?)";
String insertSaleProperty = "INSERT INTO ErrorLogs"
+ "(Error, "
+ "Time, "
+ "(?,?)";
Should probably be:
String insertSaleProperty = "INSERT INTO ErrorLogs "
+ "(Error, Time) "
+ "VALUES (?,?)";