且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Java 中将变量作为字符串插入 MySQL

更新时间:2023-02-18 20:55:39

通常,您可以使用以下方法创建带有占位符的字符串:

In general you can create strings with placeholders using:

String result = String.format("%s,%s", v1, v2);

如果您使用的是 JDBC,则可以使用 PreparedStatement,例如:

If you are using JDBC, you can use a PreparedStatement, for example:

PreparedStatement statement = connection.prepareStatement("UPDATE table1 SET column1 = ? WHERE column2 = ?");
int i = 1;
statement.setInt(i++, v1);
statement.setInt(i++, v2);
statement.executeUpdate();

对于创建 JDBC 查询,PreparedStatement 更可取,因为它可以防止输入和字符转义问题.

For creating JDBC queries the PreparedStatement is preferable because it guards you against typing and character escaping problems.

根据请求,另一种方式(虽然不知道它是否更好):

Per request, an alternative way (don't know if it's better though):

MessageFormat form = new MessageFormat("{0},{1}");
Object[] args = new Object[] {v1, v2}; // achtung, auto-boxing
String result = form.format(args)

(这个在房子里,但未经测试)

(this one is on the house, but untested)