如何在 Java 中将变量作为字符串插入 MySQL [英] How to insert variable as a string into MySQL in Java
问题描述
假设我有两个变量并且我知道它们的值:
Suppose I have two variables and I know their values:
v1=11.1f
v2=22.2f
我可以通过这种方式在字段中插入一串"11.1,22.2"
.
I can insert a string of "11.1,22.2"
into a field in this way.
PreparedStatement pstmt = null;
pstmt = conn.prepareStatement(insertQuery);
pstmt.setString(1, "11.1,22.2");
但是如果我不知道他们的价值观怎么办.如果我按照以下方式进行,
but what should I do if I do not know their values. If I do it in the following way,
pstmt.setString(1, "v1,v2");
它也是一个字符串,但是 v1 和 v2 只是字符而不是变量.
it is also a string, however, v1 and v2 are just characters but not variables any more.
那么如何将变量而不是它们的值放入字符串中,然后在需要时检索它们的值.
So how to put variables instead of their values into a String and then I retrieve their values when I need them.
我问这个问题的原因是我想在 MySQL 中将一个 ArrayList 放在一行中.如果是这样,我想我需要将 float[] 作为一个字符串放在一个字段中.请告诉我会有另一种方法来做到这一点.
That reason why I asked this question is because I want to put an ArrayList in one row in MySQL. If so I thought I need to put float[] as a string in one field. Please tell me there will be another way to do it.
推荐答案
通常,您可以使用以下方法创建带有占位符的字符串:
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)
这篇关于如何在 Java 中将变量作为字符串插入 MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!