My SQLlite database uses the format yyyy-mm-dd for dates. When I get a resulset from my database, I want to store the day of birth I got from my database by using a method from a different class. However, i'm not sure how to store it.
public void setBirthDay(LocalDate birthDay) {
this.birthDay = birthDay;
}
try (PreparedStatement stmt = conn.prepareStatement(
"select id, naam, voornaam, birthday, opmerking, debetstand_limiet, actief from klant where id = ?");) {
stmt.setInt(1, id);
stmt.execute();
try (ResultSet r = stmt.getResultSet()) {
Klant k = new Klant();
if (r.next()) {
k.setBirthDay(r.getDate("birthday").toLocalDate());
}
This is what I'm trying now, but is this even correct? The format is in LocalDate already, so why would i have to change it to LocalDate still? What is correct to do in this scenario?
String theOtherDay = "2011-07-12";
LocalDate today = LocalDate.now();
LocalDate tod = LocalDate.parse(theOtherDay);
System.out.println(today.toString());
System.out.println(tod.toString());
//2016-07-19
//2011-07-12
you can store the LocalDates objects in an arrayList if need be.
Related
I am trying to read an Excel Date value and store it into my database.
The following code is what I've got:
Date birthdate = null;
case 8:
birthdate = cell.getDateCellValue();
break;
The switch case is to store the Date in a variable and to put it into an array afterwards.
Identity id = new Identity(BSN, sort, birthdate, place);
I store multiple of those values into an arraylist.
for(Identity id : Identities) {
System.out.println(id.toString());
idmc.insertID(""+id.getBSN(), id.getSort(), id.getBirthdate(), id.getPlace());
}
The getter and setter for date is obvious, but I'll post it just in case.
public void Birthdate (Date birthdate) {
this.birthdate = birthdate;
}
public Date getBirthdate() {
return birthdate;
}
Then to insert the values I get from the Array, I use this method:
public String insertID(String BSN, String SoortID, Date UitgiftedatumID, String UitgifteplaatsID) {
String returning = null;
try {
query = "insert into Identiteit values(?,?,?,?);";
pst = connection.prepareStatement(query);
pst.setInt(1, Integer.parseInt(BSN));
pst.setString(2, Sort);
pst.setDate(3, birthdate);
pst.setString(4, place);
int response = pst.executeUpdate();
returning = response +" Records has/have been edited";
} catch (SQLException e) {
returning = " ";
}
return returning;
}
However, the line: pst.setDate(3, UitgiftedatumID); says: Incomatible types: java.util.Date cannot be converted to java.sql.Date.
I've tried casting like: pst.setDate(3, (java.sql.Date) UitgiftedatumID);
But unfortunately that didn't work out for me.
There are two Date classes in Java: java.util.Date (a general-purpose date-time class) and java.sql.Date (JDBC-related class that represents date (with no time component)). PreparedStatement#setDate() method accepts the latter as its second parameter.
To convert an instance of java.util.Date to an instance of java.sql.Date, you could do the following:
java.util.Date UitgiftedatumID = ... // some value
java.sql.Date sqlDate = UitgiftedatumID == null ? null : new java.sql.Date(UitgiftedatumID.getTime());
I am a total noob to java and sqlite. This should be simple, but I have tried and searched and can't get it to work. I have a date field in SQL that I am formatting as a sql date (MM/dd/yy). I want to delete based on a date passed. For the moment, I am only trying to display rows based on a passed date.
My code to run the query is:
String query = "select * from Peter1Score where DateSort='"+convertSQLDate("09/20/15")+"'";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
My converSQLDate() is:
public static java.sql.Date convertSQLDate (String sqlDateIn)
{
java.sql.Date returnDate = null;
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date parsed;
try
{
parsed = formatter.parse(sqlDateIn);
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
returnDate = sqlDate;
}
catch (ParseException e)
{
e.printStackTrace();
}
return returnDate;
}
I am passing 09/20/15 just for test. I have a record with that date, but it doesn't get selected.
You're not binding any variables into the statement (using the setXY() methods of PreparedStatement). Instead, you're concatenating a string value (result of Date.toString()) into the query literal.
Try this instead:
String query = "select * from Peter1Score where DateSort=?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setDate(1, convertSQLDate("09/20/15"));
When I convert String date like "18/09/13,02:01:51"
Using this method:
public static Date stringToDateFormat(String dateString) {
Date date = null;
try {
date = new SimpleDateFormat("dd/MM/yy,hh:mm:ss").parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
When I save this convert this date object to SQL Date and store it in PostgreSQL Database, I lose the time
2013-09-18 00:00:00
Here the DB insertion code"
String query = "INSERT INTO My_Table(my_date) VALUES (?)";
Date date = stringToDateFormat("18/09/13,02:01:51");
preparedStatement = connection.prepareStatement(query);
preparedStatement.setDate(1, new java.sql.Date(date.getTime()));
preparedStatement.executeUpdate();
Is it coding problem or DB configuration?
Thanks.
Your date string does not specify ms and is being rounded.
18/09/13,02:01:51 == 1379458917000
18/09/13,02:01:51.590 == 1379458917590
Update:
A format string which captures MS would be: dd/MM/yy,hh:mm:ss.SSS
I have a column in database having datatype DATETIME. I want to set this column value to current date and time using `PreparedStatement. How do I do that?
Use PreparedStatement#setTimestamp() wherein you pass a java.sql.Timestamp which is constructed with System#currentTimeMillis().
preparedStatement.setTimestamp(index, new Timestamp(System.currentTimeMillis()));
// ...
Alternativaly, if the DB supports it, you could also call a DB specific function to set it with the current timestamp. For example MySQL supports now() for this. E.g.
String sql = "INSERT INTO user (email, creationdate) VALUES (?, now())";
Or if the DB supports it, change the field type to one which automatically sets the insert/update timestamp, such as TIMESTAMP instead of DATETIME in MySQL.
conn = getConnection();
String query = "insert into your_table(id, date_column) values(?, ?)";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, "0001");
java.sql.Date date = getCurrentDatetime();
pstmt.setDate(2, date);
Where the function getCurrentDatetime() does the following:
public java.sql.Date getCurrentDatetime() {
java.util.Date today = new java.util.Date();
return new java.sql.Date(today.getTime());
}
here is the code
String DateOfBirth[]=strDOB.split("/");
Date dateOfBirth = new Date();
dateOfBirth.setYear(Integer.parseInt(DateOfBirth[2].trim()));
dateOfBirth.setMonth(Integer.parseInt(DateOfBirth[1].trim()));
dateOfBirth.setDate(Integer.parseInt(DateOfBirth[0].trim()));
java.text.SimpleDateFormat DateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
strDOB = DateFormat.format(dateOfBirth);
DBProcess.QueryExecuter("INSERT INTO patients(patient_id,first_name,last_name,middle_name,birth_dt) VALUES (\""+Double.parseDouble(strPatientID.trim())+"\",\""+strFirstname+"\",\""+strLastname+"\",\""+strMiddlename+"\",\""+strDOB +"\");");
Oh, my.
See if this is better:
private static final String INSERT_SQL = "insert into patients(patient_id, first_name, last_name, middle_name, birth_dt) values(?, ?, ?, ?, ?)";
DateFormat inputFormatter = new SimpleDateFormat("dd/MM/yy");
Date dob = inputFormatter.parse(strDOB);
PreparedStatement ps = connection.prepareStatement(INSERT_SQL);
// bind your values here.
int numRowsAffected = ps.executeUpdate();
I can't understand why you'd write that code to parse a date string when DateFormat was born to do it. And I certainly hope that your birth_dt column is of type Date in your database. Anything else is utterly foolish.
In your code, do you use java.util.Date or java.sql.Date ?
The best way to insert a Java date in MySQL (or other DB) is to use the PreparedStatement, and the java.sql.Date class :
java.sql.Date theDate = new Date(longTime);
PreparedStatement stmt = conn.prepareStatement("INSERT INTO table(id,date) VALUES (?,?)");
stmt.setInt(1, 123);
stmt.setDate(2, theDate);
stmt.execute();