【问题标题】:Android bulk insert syntax error near ","“,”附近的Android批量插入语法错误
【发布时间】: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


【解决方案1】:

多值语法是added in sqlite 3.7.11。许多设备ship with an older version.

为了兼容性,一次只插入一行。对于性能,请考虑以下几点:

  • 使用compileStatement() 预编译您的SQL,只需更改每一行的绑定参数。

  • 将插入包装在事务中以最大程度地减少 I/O 等待。

【讨论】:

  • 将研究 compileStatement() 并稍后报告。
【解决方案2】:

已提出类似问题:

SQL - Syntax error near ','

这可能不是语法错误,而是时间/拥挤错误。

【讨论】:

  • 我看到了这个问题并检查了答案。我用“;”结束我的查询,并且没有“杂散”引号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-11
  • 1970-01-01
  • 2015-03-25
  • 1970-01-01
  • 2017-10-18
  • 1970-01-01
  • 2020-09-11
相关资源
最近更新 更多