简体   繁体   中英

Call a function from a field in Java PreparedStatement?

Having a PreparedStament, I have a field of type timestamp and I don't want to set it to a fixed value but call NOW() instead. How do I do that?

I tried:

statement.setString(11, "NOW()")

but that tries to set the field to the string "NOW()" instead of calling NOW().

Thanks.

You cannot do that. But in the SQL of the prepared statement, instead of using ? , you can use NOW() .

Alternatively, you can keep the ? in the SQL, and do statement.setDate( 11, new Date() );

Call preparedStatement.setTimeStamp(11, LocalDateTime.now().toString())

If you aren't using Java 8, or want to learn how to get the current time as a String, see this .

It seems you are willing to call mysql now() function that returns the current date-time stamp.

If so, then you must put now() in queryString as "String part of the query", if you try to put it using preparedStatement then it will be treated as pure string value not as mysql function. ... see this http://www.mysqltutorial.org/mysql-now/

  • OR

If you want to call a java code function named now() then remove the double quotes from it and make sure it returns String .

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