0

I would appreciate a shade of enlightenment on the following code, since I just can't seem to figure out why it has a syntax error near ",".

I'm trying to insert multiple rows at once in a single statement. I'm targeting API 10+. If I only have one set of VALUES(...) it's all good, and the row gets inserted, but as soon as I have more than one, it sends out an exception with the syntax error message.

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();

I print the query out on my log and get:

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');

Help is very much appreciated.

Chayemor
  • 3,577
  • 4
  • 31
  • 54

2 Answers2

1

The multi-values syntax was added in sqlite 3.7.11. Many devices ship with an older version.

For compatibility, insert only one row at a time. For performance, consider the following:

  • Use compileStatement() to pre-compile your SQL and just change the bind args for each row.

  • Wrap the inserts in a transaction to minimize waiting on I/O.

Community
  • 1
  • 1
laalto
  • 150,114
  • 66
  • 286
  • 303
-1

Similar questions have been asked:

SQL - Syntax error near ','

It might be less of a syntax error and more of a timing/crowding error.

Community
  • 1
  • 1
John O.
  • 98
  • 7
  • I saw that question and have checked for the answer. I end my query with ";" , and have no "stray" quotes. – Chayemor Mar 26 '14 at 00:21