如何从安卓工作室的SQLite插入中删除不需要的字符



当我通过 JSON 从服务器传递数据时。我收到此错误。

android.database.sqlite.SQLiteException: near "rusitha": syntax error (code 1): , while compiling: INSERT INTO customer (id, name,nic,areaId,tp,address) VALUES ('583', 's.p.m.j.ilangasinghe.', '805250666v','18','0716090398','no.79,'rusitha',nuwarapara,maradankadawala.');

这是我使用的代码。

for(i = 0;i<customerId.length();i++){
sqlite.execSQL("INSERT INTO customer (id, name,nic,areaId,tp,address) VALUES ('"+customerId.get(i).toString()+"', '"+customerName.get(i).toString()+"', '"+customerNIC.get(i).toString()+"','"+customerAreaId.get(i).toString()+"','"+customerTp.get(i).toString()+"','"+customerAddress.get(i).toString()+"');");
}

问题是'no.79,没有结束单引号。这是因为rushita括在单引号中,前面有一个逗号。简而言之,地址没有被正确转义,因此 rushita 周围的单引号会混淆 SQLite。

您的选择是将地址中的单引号替换为 2 个单引号,例如

customerAddress.get(i).toString().replace("'","''")

或者通过使用扩展签名execSQL方法使用绑定来代表您完成此操作。

sqlite.execSQL("INSERT INTO customer (id, name,nic,areaId,tp,address) VALUES (?,?,?,?,?,?)"), newString[]{customerId.get(i).toString(),customerName.get(i).toString(),customerNIC.get(i).toString(),customerAreaId.get(i).toString(),customerTp.get(i).toString(),customerAddress.get(i).toString()});
  • 建议绑定而不是以前的方法。

另一种方法是使用插入便利方法,例如

ContentValues cv = new ContentValues();
cv.put("id",customerId.get(i).toString());
cv.put("name",customerName.get(i).toString());
cv.put("nic",customerNIC.get(i).toString());
cv.put("areaId",customerAreaId.get(i).toString());
cv.put("tp",customerTp.get(i).toString());
cv.put("address",customerAddress.get(i).toString());
long insertedId = sqlite.insert("customer",null,cv);
  • 这将是最推荐的方式。

    • 它代表您构建 SQL,
    • 绑定值,
    • 返回插入行的 rowid
    • 当它绑定值时,它就像扩展的execSQL一样,可以防止SQL注入。

注意上面的代码是原则上的代码,没有经过检查、测试或运行,所以可能会有一些小错误。

您可以在使用字符之前正确转义您获得的 JSON 数据:

// JSON Escape Utility
public static String crunchifyJSONEscapeUtil(String crunchifyJSON) {
final StringBuilder crunchifyNewJSON = new StringBuilder();
// StringCharacterIterator class iterates over the entire String
StringCharacterIterator iterator = new StringCharacterIterator(crunchifyJSON);
char myChar = iterator.current();
// DONE = \uffff (not a character)
while (myChar != StringCharacterIterator.DONE) {
if (myChar == '"') {
crunchifyNewJSON.append("\"");
} else if (myChar == 't') {
crunchifyNewJSON.append("\t");
} else if (myChar == 'f') {
crunchifyNewJSON.append("\f");
} else if (myChar == 'n') {
crunchifyNewJSON.append("\n");
} else if (myChar == 'r') {
crunchifyNewJSON.append("\r");
} else if (myChar == '\') {
crunchifyNewJSON.append("\\");
} else if (myChar == '/') {
crunchifyNewJSON.append("\/");
} else if (myChar == 'b') {
crunchifyNewJSON.append("\b");
} else {
// nothing matched - just as text as it is.
crunchifyNewJSON.append(myChar);
}
myChar = iterator.next();
}
return crunchifyNewJSON.toString();
}

代码最初来自本网站

最新更新