-
Convert date to SQL
I have a MySQL table with a date field.
This has the format "yyyy-mm-dd"
I want to convert this from a text field in my program.
I would like the users to type the date into the textfield in this format: "dd.mm.yyyy".
How can i convert this format to the MySQL format so I can insert it into the table?
-
Re: Convert date to SQL
Its simple easy if you are using PreparedStatements and SimpleDateFormat, example:
PreparedStatement date = connection.prepareStatement("INSERT INTO YOURTABLE (YOURCOLUMN) VALUES (?)");
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
date.setDate(1, new Date(formatter.parse("YOUR USER INPUT").getTime())); // java.sql.Date
date.executeUpdate();
-
Re: Convert date to SQL
Hi, thanks for the quick reply.
I think I am very close, but something is wrong:
Heres my code:
Code:
String firstname;
firstname = textFirstName.getText();
String lastname;
lastname = textLastName.getText();
String address;
address = textAddress.getText();
String zip;
zip = textZip.getText();
String city;
city = textCity.getText();
String phone;
phone = textPhone.getText();
String mobile;
mobile = textMobile.getText();
String dato;
dato = textDate.getText();
SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yyyy");
Connection connection = Connector.getConnection();
PreparedStatement ps = null;
String query = "INSERT INTO ContactTable(FirstName, LastName, Address, Zip, City, Phone, MobilePhone, Date)"
+" VALUES(?,?,?,?,?,?,?,?)";
try {
ps = connection.prepareStatement(query);
ps.setString(1, firstname);
ps.setString(2, lastname);
ps.setString(3, address);
ps.setString(4, zip);
ps.setString(5, city);
ps.setString(6, phone);
ps.setString(7, mobile);
ps.setDate(8, new Date(sdf.parse(dato).getTime()));
ps.executeUpdate();
I have a error on the setDate line...:=(:
-
Re: Convert date to SQL
What does the error message say?
Dou you have seen my comment at that line?
ps.setDate(8, new java.sql.Date(sdf.parse(dato).getTime()));
-
Re: Convert date to SQL
Thanks for the help, I got it to work! :(happy):
Code:
try {
ps.setDate(8, new java.sql.Date(sdf.parse(dato).getTime()));
} catch (ParseException ex) {
Logger.getLogger(ContactForm.class.getName()).log(Level.SEVERE, null, ex);
}
ps.executeUpdate();
And I had written a little typeo in the dateformat:
My code:
Code:
SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yyyy");
Corrected to this:
Code:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Works perfectly!
-
Re: Convert date to SQL
New question: I also wants to display this date. How is that code?