简体   繁体   中英

Android insert into sqlite database

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!

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.

The right answer is given by the CommonsWare in comments. You should be using execSql() instead of rawQuery(). And it works like a charm.

I thought it would be useful for others, not to have to dig through the comments to find the right answer.

Since it is a string values you forgot "'" to add...this query will surely work, i tested

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM