简体   繁体   English

使用FMDB写入SQLite数据库?

[英]Writing to sqlite db using fmdb?

Ok so I understand that fmdb is totally outdated, and core data is where it's at, but for now, I just need to tweak an app I'm working on that uses fmdb to read from a sqlite db in the resources folder. 好的,所以我知道fmdb已经完全过时了,核心数据就在其中,但是现在,我只需要调整一个正在使用的应用程序,该应用程序使用fmdb从资源文件夹中的sqlite数据库中读取数据。

I need to be able to write to my db. 我需要能够写入我的数据库。 What is the best way to execute queries? 什么是执行查询的最佳方法? I have tried doing the same thing that I do to read from a db: 我尝试做与从数据库读取相同的操作:

FMResultSet * set = [[UIApp database] executeQuery:[customQueries selectAll], book];

Where I change the string selectAll from being a SELECT statement into being a INSERT INTO statement and I pass it the variable book to insert, but that doesn't seem to be working... 我将selectAll字符串从SELECT语句更改为INSERT INTO语句,然后将要插入的变量书传递给它,但这似乎不起作用。

What am I missing? 我想念什么? What do I nee to do to be able to write to my sqlite db?? 我需要做什么才能能够写入我的sqlite数据库? Thanks! 谢谢!

To insert you would do something like this, where db is a reference to your FMDatabase: 要插入,您将执行以下操作,其中db是对FMDatabase的引用:

[db executeUpdate:@"insert into theTable (field1, field2) values(?, ?)", 
    theField1, theField2, nil];

Make sure there is a nil at the end of the parameter list (2 question marks in the query means two parameters and a nil), and make sure that you are using NS types as the parameters. 确保参数列表的末尾有一个nil(查询中的2个问号表示两个参数,一个nil),并确保您使用NS类型作为参数。 If you try to use an int as a parameter, it will crash, you would need to use an NSNumber instead. 如果尝试将int用作参数,则它将崩溃,您将需要使用NSNumber代替。

FMDatabase* db = [FMDatabase databaseWithPath:dbPath];

FMResultSet *rs = [db executeQuery:@"select * from table"];
while ([rs next]) {
    NSLog(@"%d", [rs intForColumn:@"id"];
}

// Close the result set.
[rs close];  

// Close the database.
[db close];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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