tags:

views:

1717

answers:

2

I know there is probably a simple thing I'm missing, but I've been beating my head against the wall for the past hour or two. I have a database for the Android application I'm currently working on (Android v1.6) and I just want to insert a single record into a database table. My code looks like the following:

//Save information to my table
sql =   "INSERT INTO table1 (field1, field2, field3) " +
        "VALUES (" + field_one + ", " + field_two + ")";
Log.v("Test Saving", sql);
myDataBase.rawQuery(sql, null);

the myDataBase variable is a SQLiteDatabase object that can select data fine from another table in the schema. The saving appears to work fine (no errors in LogCat) but when I copy the database from the device and open it in sqlite browser the new record isn't there. I also tried manually running the query in sqlite browser and that works fine. The table schema for table1 is _id, field1, field2, field3.

Any help would be greatly appreciated. Thanks!

A: 

I changed my code to use myDataBase.insert() instead of rawQuery() and it's working. I'm not sure why the actual sql query didn't work though, so if anyone can shed some light on that I'd still appreciate it.

Josh
If what you posted is the exact query, it's because you're specifying 3 fields but only passing 2 values.
tadamson
`rawQuery()` is for queries. An `INSERT` statement is not a query. If you want to execute raw SQL that does not return a result set, use `execSQL()`.
CommonsWare
Ah, execSql() is what I needed then. And yes, I was passing 3 values in my code but it got lost in the code cleanup when I pasted it over here. Thanks!@CommonsWare, if you post that as an answer here I will give you credit for solving it.
Josh
+1  A: 

Your query is invalid because you are providing 2 values for 3 columns. Your raw query should look like:

sql = "INSERT INTO table1 (field1, field2) " +
    "VALUES (" + field_one + ", " + field_two + ")";

although your schema contains three fields. By the way, you can see the log to see the actual error reporting from sqlite.

Burcu Dogan
I cleaned up the code some and accidentally removed the third field in the values section. Good catch though.
Josh