开发者

Using SQL function in parameterized statement

开发者 https://www.devze.com 2023-01-14 10:13 出处:网络
Considering this query: insert (a, b, update_time) values (1, 1, now() - interval 10 second) Now, I need to convert it to a parameterized statement:

Considering this query:

insert (a, b, update_time) values (1, 1, now() - interval 10 second)

Now, I need to convert it to a parameterized statement:

insert (a, b, update_time) values (?, ?, ?) 

The pr开发者_JS百科oblem is you cannot use SQL function in the parameter. How do I write this kind of code?


Date now = new Date();
PreparedStatement ps = connection.prepareStatement("INSERT INTO your_table(a, b, update_time) VALUES(?, ?, ?)");
ps.setObject(1, a);
ps.setObject(2, b);
ps.setDate(3, now);
ps.executeUpdate();


There's no need to parameterize the date code:

insert (a, b, update_time) values (?, ?, now() - interval 10 second)

Now it only takes two parameters and the date will be handled on the server. I've had timezone issues between JDBC and MySQL concerning daylight savings time. Be careful!

0

精彩评论

暂无评论...
验证码 换一张
取 消