Search code examples
javastringstringbuilderstring.format

Java StringBuilder with printf. Equivalent String.format


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?


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