【发布时间】:2014-03-25 23:23:40
【问题描述】:
我希望对以下代码有所启发,因为我似乎无法弄清楚为什么它在 "," 附近有一个语法错误。
我试图在一个语句中一次插入多行。我的目标是 API 10+。如果我只有一组 VALUES(...) 一切都很好,并且该行被插入,但只要我有多个,它就会发出带有语法错误消息的异常。
SQLiteDatabase db = getWritableDatabase();
String insertRows = "INSERT INTO " + TABLE_FRIENDS +
" (" + KEY_USER_EMAIL + ", " + KEY_FRIEND + ", " + KEY_FRIEND_INTERACTIONS +
", " + KEY_ENABLED +") VALUES ";
int index;
for(index=0; index<friends.size(); ++index){
insertRows += "('" + userAccount.getEmail() +"', ";
Friend friend = friends.get(index);
insertRows+= "'" + friend.getEmail() +"', ";
insertRows+= "'" + friend.getInteractions() +"', ";
int enabled = friend.isEnabled() ? 1 : 0;
insertRows+= "'"+ enabled + "')";
if(index != friends.size()-1)
insertRows+= ",";
}
insertRows += ";";
db.execSQL(insertRows);
db.close();
我在日志上打印查询并得到:
INSERT INTO friends (user_email, friend_email, friend_interactions, friend_enabled) VALUES ('test2@test.com', 'vila@hotmail.com', '0', '0'),
('test2@test.com', 'anotherone@hotmail.com', '0', '0'),
('test2@test.com', 'yetanother@hotmail.com', '0', '0');
非常感谢您的帮助。
【问题讨论】:
-
而不是像这样构建插入查询,为什么不使用 contentvalues 并执行插入?你无论如何都在运行一个循环
-
我认为针对具有所有值的单个插入,多次插入对性能不利。
-
是的,这很糟糕,但我怀疑第一个值组合之后的
,是否会导致问题,或者在 android 中搜索批量插入,并且 ul 使用插入帮助程序获得更好的解决方案,但它已弃用。
标签: android sqlite bulkinsert