简体   繁体   中英

Insert datetime string from java in MySQL

Hi all i have a problem in a insert query.

I get datetime from java with:

SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
String strDate = sdfDate.format(now);

ps: I have try a sysout on strDate and it is correct.

I read a question, like that, where to enter in MySQL datetime must make a query like this:

INSERT INTO tracks (in) VALUES (STR_TO_DATE( ? ,'%Y-%m-%d %r'))

Where '?' is the string containing the date, but it don' t work.

Can anyone help me?

UPDATE: MySQL Server 5.7

You have use current time. So you can do it simply with NOW().

INSERT INTO tracks (`in`) VALUES (NOW())

OR

You can do this way

java.sql.Timestamp now = new java.sql.Timestamp(new java.util.Date().getTime());
PrepStmt.setTimestamp(1, now);

I have found the problem.

The name "in" for the DateTime field is not accepted.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'in, session) VALUES (1, NOW(), "abc")' at line 1.

'in, session)

I have try to rename it in "indate" and the query:

INSERT INTO tracks (fk_utenza, indate, session) VALUES (1, NOW(), "abc");

works well!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM