我在用
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"})
我想使用 log.v 输出 sql 插入。
1 用String数组替换%s叫什么,替换'?'的名称是什么用字符串数组?我经常在 c 语言中注意到这种策略,但从来不知道它叫什么或如何用谷歌搜索它。
2 formatter或其他方法是否可以直接进行上述替换?
我尝试了什么:
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
最佳答案
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
这两种解决方案都可以。请注意,在第一个版本中,执行查询时仍应使用原始字符串,而不是格式化后的字符串。如您所述,查询的格式化版本会将所有类型转换为字符串。这将允许 SQL 引擎使用正确的类型和正确的引用来避免 SQL 注入(inject)。
关于java - java String.format 可以处理替换吗?而不是 %s,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41747294/