[Solved] How to insert variable as a string into MySQL in Java


In general you can create strings with placeholders using:

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

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();

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

EDIT: 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)

4

solved How to insert variable as a string into MySQL in Java