Java 的 PreparedStatement 是如何工作的? [英] How does Java's PreparedStatement work?
问题描述
我计划用 PreparedStatement
对象替换重复执行的 Statement 对象以提高性能.我正在使用像 MySQL 函数 now()
和字符串变量这样的参数.
I am planning to replace repeatedly executed Statement objects with PreparedStatement
objects to improve performance. I am using arguments like the MySQL function now()
, and string variables.
我见过的大多数 PreparedStatement
查询都包含常量值(如 10
和字符串如 "New York"
)作为使用的参数对于查询中的 ?
.我将如何使用像 now()
这样的函数和变量作为参数?是否有必要在查询中使用 ?
而不是实际值?我很困惑.
Most of the PreparedStatement
queries I have seen contained constant values (like 10
, and strings like "New York"
) as arguments used for the ?
in the queries. How would I go about using functions like now()
, and variables as arguments? Is it necessary to use the ?
s in the queries instead of actual values? I am quite confounded.
推荐答案
如果您有变量,请使用 '?'
If you have variables use the '?'
int temp = 75;
PreparedStatement pstmt = con.prepareStatement(
"UPDATE test SET num = ?, due = now() ");
pstmt.setInt(1, temp);
pstmt.executeUpdate():
生成如下所示的 sql 语句:
Produces an sql statment that looks like:
UPDATE test SET num = 75, due = now();
这篇关于Java 的 PreparedStatement 是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!