0

I can not understand why I was trying to insert some records using the method rawQuery, for example:

db.rawQuery("INSERT INTO table (name, desc) VALUES ('Name1', 'Desc1');", null);

But this does not seem to work, in fact, trying with the insert() method works all:

ContentValues fields = new ContentValues();
fields.put("name", "Nome1");
fields.put("desc", "Desc1");
db.insert("table", null, fields);

And I wonder why this.

mikelplhts
  • 1,181
  • 3
  • 11
  • 32

1 Answers1

5

rawQuery() is for SQL statements that return a result set. Use execSQL() for SQL statements, like INSERT, that do not return a result set.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Unfortunately, the documentation for execSQL(query, args) says "Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE". What do you do when you need selection args? And is execSQL(query) really meant for INSERT statements when execSQL(query, args) explicitly isn't? (And there's no explicit documentation that says rawQuery() is not for queries that don't return a result set.) – LarsH Apr 08 '21 at 19:57
  • @LarsH: "Unfortunately, the documentation for execSQL(query, args) says" -- that's an over-zealous bit of documentation. If you look at the implementation of `SQLiteDatabase`, both forms of `execSQL()` call the same internal method. "And there's no explicit documentation that says rawQuery() is not for queries that don't return a result set" -- if you mean "statements" where you have "queries", IIRC, you crash. "What do you do when you need selection args?" -- use the two-parameter `execSQL()`, despite the docs. – CommonsWare Apr 08 '21 at 20:10
  • ' if you mean "statements" where you have "queries", IIRC, you crash' - No, not when I've tried it. "both forms of execSQL() call the same internal method" - which could well be interpreted to mean that we shouldn't use either one with SELECT/INSERT/UPDATE/DELETE. – LarsH Apr 08 '21 at 21:12
  • @LarsH: Um, well, they work. For example, Room's generated code uses them for setup (`_db.execSQL("INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '051fc3ca1ecb3344055fd77365a9bf8e')");`) and cleanup (`_db.execSQL("DELETE FROM `notes`");`). Though another option for you would be to create and bind a `SQLiteStatement`, which is what Room uses for DAO CRUD operations. – CommonsWare Apr 08 '21 at 21:47