Reputation: 20856
I'm trying to use a string formatter but its not working as expected..
When I print the SQL_QUERY
, it prints only TABLE1
, I want the overall result "SELECT * FROM TABLE1"
package mysql.first;
public class twoconstructor {
public static void main(String[] args) throws Exception {
final String SQL_QUERY = "SELECT * FROM %s ".format("TABLE1");
}
}
Upvotes: 0
Views: 81
Reputation: 124225
String.format
is static method that takes String format, Object... args
where first argument is format, and rest is its arguments. If you want to use this method your code should look like this
String SQL_QUERY = String.format( "SELECT * FROM %s ", "TABLE1")
But never use String.format
to create sql query. Instead to avoid SQL injection use PreparedStatements. Take a look also at this example.
Upvotes: 2
Reputation: 49372
You are not calling the method in a right way :
final String SQL_QUERY = String.format ("SELECT * FROM %s ","TABLE1");
You should have read the warnings in your IDE.
Read the documentation.
Note the second argument is a vararg Object... args
, hence it compiled fine.
Upvotes: 2
Reputation: 15552
I think it has to be
String.format("select * from %s", "TABLE 1");
This is due to the odd thing in java that you can run static methods against object instances so it can be confusing. Your object instance in this case is "SELECT * FROM %s " (This is one of my biggest annoyances because it causes confusion like this)
Take a look at the docs . The args element is varargs so it can actually take no parameters.
Upvotes: 6