1

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?

3 Answers 3

5

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");
Sign up to request clarification or add additional context in comments.

4 Comments

Same answer, But I was too quick
@nelsonjuan What are trying to do here by appending ?
@Ruchira I am actually using javax.persistence.EntityManager to take care of the database. I am preparing the String to em.createNativeQuery(sb.toString(), SomeClass.class).getResultList()
@nelsonjuan You can set parameters for EntityManager's native queries using setParameter
1

This may help you. where the con is connection

    PreparedStatement preStatement = con.prepareStatement("select * from x where name = ?");
    preStatement.setString(1, "John");

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.