Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

e.g

/**
 * 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();
}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top