Android插入sqlite数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2616130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android insert into sqlite database
提问by Blather
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:
我知道我可能遗漏了一件简单的事情,但过去一两个小时我一直在用头撞墙。我有一个用于当前正在开发的 Android 应用程序(Android v1.6)的数据库,我只想将一条记录插入到数据库表中。我的代码如下所示:
//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.
myDataBase 变量是一个 SQLiteDatabase 对象,它可以从架构中的另一个表中选择数据。保存似乎工作正常(LogCat 中没有错误)但是当我从设备复制数据库并在 sqlite 浏览器中打开它时,新记录不存在。我还尝试在 sqlite 浏览器中手动运行查询,效果很好。table1 的表架构是 _id、field1、field2、field3。
Any help would be greatly appreciated. Thanks!
任何帮助将不胜感激。谢谢!
回答by Burcu Dogan
Your query is invalid because you are providing 2 values for 3 columns. Your raw query should look like:
您的查询无效,因为您为 3 列提供了 2 个值。您的原始查询应如下所示:
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.
尽管您的架构包含三个字段。顺便说一下,您可以查看日志以查看sqlite 的实际错误报告。
回答by Micha? K
The right answer is given by the CommonsWare in comments. You should be using execSql() instead of rawQuery(). And it works like a charm.
CommonsWare 在评论中给出了正确的答案。您应该使用 execSql() 而不是 rawQuery()。它就像一个魅力。
I thought it would be useful for others, not to have to dig through the comments to find the right answer.
我认为这对其他人很有用,而不必通过挖掘评论来找到正确的答案。
回答by Maddy J
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 + "')";
回答by Blather
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.
我将代码更改为使用 myDataBase.insert() 而不是 rawQuery() 并且它正在工作。我不确定为什么实际的 sql 查询不起作用,所以如果有人能对此有所了解,我仍然会很感激。