1

Will MySQL allow me to insert a properly formatted string into a datatime field in my MySQL database?

I am parsing a file, combining dates of format yyyyMMdd and times of format HHmmss, and planning to format them into a string like:

     "yyyy-MM-dd HH:mm:ss"

I would like to then insert this string into my datetime field (which has the same formatting as the example above" with a insert query.

If this isn't the proper way to handle my problem, what method should I be using? After looking at the MySQL documentation I got the impression that I could do this as long as the formatting was correct. Working with Java's Calendar and Date classes seemed to only have headaches in store for me.

4 Answers 4

2

This isn't the proper way to do that. The proper way is to use a java.sql.Timestamp, and use a prepared statement to insert your date:

Date date = dateFormat.parse(s);
Timestamp timestamp = new Timestamp(date.getTime());
String sql = "insert into my_table (id, instant) values(?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setLong(1, id);
stmt.setTimestamp(2, timestamp);
stmt.executeUpdate();

This will make your code portable, not tied to any locale or database.

Sign up to request clarification or add additional context in comments.

2 Comments

I had completely overlooked the final paragraph of the question (and its tags)! iFail. +1
So you recommend this method over what you suggested? @eggyal Is the problem that mine just isn't the proper way to do it?
1

As discussed in the manual, there are a number of valid formats for datetime literals of this sort, including that which you propose.

So yes, this will work exactly as you describe. Note however you needn't add the additional formatting, as you could just insert YYYYMMDDHHMMSS directly—it needn't even be quoted as a string.

1 Comment

Thanks. I hadn't come across that yet. I had been reading this
0

Yes that would work. MySQL uses the format yyyy-MM-dd HH:mm:ss as its default, but as mentioned, you can use a number of other formats.

If you'd like to check for a valid date, try to perform a idempotent operation on the date.

SELECT 'mydate' + INTERVAL 0 DAY

If MySQL returns the same thing back to you, the date is valid, otherwise MySQL will return NULL.

Comments

0

You can use a String if it's formatted correctly. I do it in my code and have a TimeUtil class that converts longs to the prescribed format for the DB.

I can then simply use the statement like

stat.setString(10, TimeUtil.formatTime(message.submitTime));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.