Then Enok
Then Enok

Reputation: 661

Can java String.format handle replacing ? instead of %s

I'm using

db.execSQL("INSERT INTO table SELECT NULL WHERE '1'=?;",new String[]{"1"});
db.execSQL("INSERT INTO robot_active_variables\n" +
                    "SELECT NULL, ravs._id,str,val\n" +
                    "FROM ( SELECT 'is_answer' AS str, ? AS val\n" +
                    "UNION ALL SELECT 'is_setting', ?\n" +
                    "UNION ALL SELECT 'is_val', ?\n" +
                    "UNION ALL SELECT 'is_group_actions', ?\n" +
                    "UNION ALL SELECT 'is_lone_action', ?\n" +
                    "UNION ALL SELECT '_id', ?\n" +
                    "UNION ALL SELECT 'val', ? ) v\n" +
                    "join robot_active_variables_super ravs on ravs._id not in (select _id_parent from robot_active_variables);",new String[]{"1", "0", "0", "0", "0", String.valueOf(idAnswer), "0"})

And I want to use log.v to output the sql inserts.

1 What's it called to replace %s with String array, and what's the name for replacing '?' with String array? I noticed this strategy very often in c but never knew what's it called or how to google it.

2 Can formatter or any other method do the above replacements directly?

What i tried:

v1: Log.v("custom log.v call " , sql + bindArgs));
but i had to copy paste every var into the "?"

v2: Log.v("custom log.v call " , String.format(sql.replaceAll("\\?","%s"),bindArgs));
but then some queries didn't work, it seems that numbers are converted to text, ie: 'select 1=?' with new String[]{"1"} will give false because it becomes 'select 1="1"'

v3: Log.v("custom log.v call " , String.format(sql.replaceAll("\\?","\"%s\""),bindArgs));
works quite well

Upvotes: 1

Views: 2299

Answers (1)

Code-Apprentice
Code-Apprentice

Reputation: 83527

v2: Log.v("custom log.v call " , String.format(sql.replaceAll("\\?","%s"),bindArgs));

but then some queries didn't work, it seems that numbers are converted to text, ie: 'select 1=?' with new String[]{"1"} will give false because it becomes 'select 1="1"'

v3: Log.v("custom log.v call " , String.format(sql.replaceAll("\\?","\"%s\""),bindArgs));

works quite well

Either of these solutions is fine. Note that in the first version, you should still use the original string when executing the query, not the formatted one. As you noted, the formatted version of your query will convert all types to a String. This will allow the SQL engine to use the correct types and correct quoting to avoid SQL injection.

Upvotes: 1

Related Questions