I am using StringBuilder to build a ver long query.
StringBuilder sb = new StringBuilder();
sb.append("select * from x where name = %s'");
String.format(sb.toString, "John");
What would be equivalent to something like this? Or is this actually the right way to do it?
It appears you are attempting to build a String for SQL
. PreparedStatement
should be used instead for this purpose.
PreparedStatement preparedStatement =
connection.prepareStatement("select * from x where name = ?");
preparedStatement.setString(1, "John");
Edit:
Given that you're using EntityManager
, you can use its equivalent setParameter
Query q =
entityManager.createNativeQuery("select * from x where name = ?", MyClass.class);
q.setParameter(1, "John");
This may help you. where the con
is connection
PreparedStatement preStatement = con.prepareStatement("select * from x where name = ?");
preStatement.setString(1, "John");
If you are not using SQL, for a general formatted append, could use Formattor
's format()
method.
eg
/**
* Generate a string that also contains data list.
*
* @return
*/
public String toStringWithDataList() {
List<T> list = toList();
StringBuilder sb = new StringBuilder(getClass().getName());
Formatter fm = new Formatter(sb);
sb.append(toString()).append(System.lineSeparator()); // basic info,
// value list,
if (size > 0) {
sb.append("list = ");
for (int i = 0; i < list.size(); i++) {
fm.format("\n\t[%d]-th: %s", i, list.get(i));
}
sb.append(System.lineSeparator());
}
return sb.toString();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.