FMDatabase 的使用方法
http://blog.sina.com.cn/s/blog_94d94f1a01015gcr.htmlFMDatabase 的使用方法 以下是FMDB的一些基本使用,FMDB框架其实只是一层很薄的封装,主要的类也就两个:FMDatabase和FMResultSet;其中的FMResultSet对象让我想起了android中sqlite的cursor集合啊。
http://blog.sina.com.cn/s/blog_94d94f1a01015gcr.html
FMDatabase 的使用方法
以下是FMDB的一些基本使用,FMDB框架其实只是一层很薄的封装,主要的类也就两个:FMDatabase和FMResultSet;
其中的FMResultSet对象让我想起了android中sqlite的cursor集合啊。
FMDB的github地址是,https://github.com/ccgus/fmdb。
补充:是导入FMDB之后,还要记得导入iOS的sqlite3Framework,libsqlite3.0.dylib,PS:我发现网上有些转载我的博文的,我很欢迎,毕竟我的一些博文也是总结别人的经验的。但是有个网站,51CTO,我觉得是让人又爱又恨的,它引用的文章从来没有过注明出处。都是佚名。这让人很无语,这是我偶然之间发现我写的东西竟然被标为佚名?
1、首先得实例化一个FMDatabase对象,这跟Sqlitepersistentobjects派生一个子类进行操作是不同。接着打开一个数据库(如果没有会创建一个数据库)
//paths: ios下Document路径,Document为中ios可读写的文件夹
//创建数据库实例 db 这里说明下:如果路径中不存在”Test.db”的文件,sqlite会自动创建”Test.db”
- NSArray
* paths= NSSearchPathForDirectoriesInDomains (NSDocumentDirectory,NSUserDomainMask, YES); - NSString
* documentDirectory= [paths objectAtIndex:0]; - //dbPath:
数据库路径,在Document中。 - NSString
* dbPath= [documentDirectory stringByAppendingPathCom ponent:@"Test.db"]; -
- FMDatabase
* db=[FMDatabase databaseWithPath:dbPath] ; - if
(![db open]) { - NSLog(@“Could
not open db.”); - return
; - }
接下来,我们可以通过这个数据库对象进行操作了。操作主要是update和queries。
首先是创建表。
//创建一个名为User的表,有两个字段分别为string类型的Name,integer类型的 Age
- [db
executeUpdate:@"CREATE TABLE User (Name text, Age integer)"];
这样我们就有了一张表了。接下我们对表进行操作。插入数据!注意插入的数据使用了通配符,这跟iphone直接使用sqlite借口的绑定变量是一样的,后面的通配符匹配的数据。
//插入数据使用OC中的类型 text对应为NSString integer对应为NSNumber的整形
- [db
executeUpdate:@"INSERT INTO User (Name,Age) VALUES (?,?)",@"老婆",[NSNumber numberWithInt:20]] ;
接下来是更新数据。
- //更新数据
将“老婆”更改为“宝贝” - [db
executeUpdate:@"UPDATE NameUser SET = Name? WHERE = ? ",@"老婆",@"宝贝"];
再接下来,就是删除数据啦。
- //删除数据
- [db
executeUpdate:@"DELETE NameFROM User WHERE = ?",@"老婆"];
update的基本操作就这几个,接下来是queries!
- //返回数据库中第一条满足条件的结果
- NSString
* aa=[dbstringForQuery:@"SELECT AgeName FROM User WHERE = ?",@"20"];
这样我们就查询返回了一条数据,那当我们想要查询放返回多条数据怎么办呢?不用愁,之前我就提到了FMDB中的另外一个主要的类,FMResultSet,这是一个结果集!返回多条数据时FMDB会将数据放在这个结果集中,然后我们在对这个结果集进行查询操作!很简单。
- FMResultSet
* rs=[dbexecuteQuery:@"SELECT * FROM User"]; - rs=[db
executeQuery:@"SELECT Age* FROM User WHERE = ?",@"20"]; - while
([rs next]){ - NSLog(@“%@
%@”,[rs stringForColumn:@"Name"],[rs stringForColumn:@"Age"]); - }
更多的FMResultSet方法有:
intForColumn:
longForColumn:
longLongIntForColumn:
boolForColumn:
doubleForColumn:
stringForColumn:
dateForColumn:
dataForColumn:
dataNoCopyForColumn:
UTF8StringForColumnIndex
objectForColumn:
- (NSString*)getPath {
}
1.创建数据库
-(void)CreateTable;
{
dataBase
}
2.查询数据
-(void)QueryData
{
//获取数据
}
3.更新数据
-(void)UpdateData
{
if
}
4。插入数据
-(void)insertData
{
//插入数据库
}
5。官方的使用方法为:
Usage
There are three main classes in FMDB:
- FMDatabase
- Represents a single SQLitedatabase. Used for executing SQL statements. - FMResultSet
- Represents the results ofexecuting a query on anFMDatabase. - FMDatabaseQueue
- If you're wanting toperform queries and updates on multiple threads, you'll want to usethis class. It's described in the "Thread Safety" sectionbelow.
Database Creation
An
- A file system path. The file does not have to exist on disk. If itdoes not exist, it is created for you.
- An empty string (@"").An empty database is created at a temporary location. This databaseis deleted with theFMDatabase
connectionis closed. - NULL. An in-memory database is created. This database willbe destroyed with theFMDatabaseconnectionis closed.
(For more information on temporary and in-memory databases, readthe sqlite documentation on the subject:http://www.sqlite.org/inmemorydb.html)
FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
Opening
Before you can interact with the database, it must be opened.Opening fails if there are insufficient resources or permissions toopen and/or create the database.
if (![db open]) {
}
Executing Updates
Any sort of SQL statement which is nota
Executing updates returns a single value,a
Executing Queries
A
Executing queries returns an
In order to iterate through the results of your query, you usea
FMResultSet *s = [db executeQuery:@"SELECT * FROM myTable"];
while ([s next]) {
}
You must always invoke
FMResultSet *s = [db executeQuery:@"SELECT COUNT(*) FROMmyTable"];
if ([s next]) {
}
FMResultSet
- intForColumn:
- longForColumn:
- longLongIntForColumn:
- boolForColumn:
- doubleForColumn:
- stringForColumn:
- dateForColumn:
- dataForColumn:
- dataNoCopyForColumn:
- UTF8StringForColumnIndex
: - objectForColumn:
Each of these methods also has a
Typically, there's no need to
Closing
When you have finished executing queries and updates on thedatabase, you should
[db close];
Transactions
FMDatabase
Data Sanitization
When providing a SQL statement to FMDB, you should not attempt to"sanitize" any values before insertion. Instead, you should use thestandard SQLite binding syntax:
INSERT INTO myTable VALUES (?, ?, ?)
The
Alternatively, you may use named parameters syntax:
INSERT INTO myTable VALUES (:id, :name, :value)
Theparameters
NSDictionary *argsDict = [NSDictionarydictionaryWithObjectsAnd
[db executeUpdate:@"INSERT INTO myTable (name) VALUES (:name)"withParameterDictionary:argsDict];
Thus, you SHOULD NOT do this (or anything like this):
[db executeUpdate:[NSString stringWithFormat:@"INSERT INTO myTableVALUES (%@)", @"this has " lots of ' bizarre " quotes '"]];
Instead, you SHOULD do:
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @"this has "lots of ' bizarre " quotes '"];
All arguments provided to the
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", 42];
The proper way to insert a number is to box it inan
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumbernumberWithInt:42]];
Alternatively, you can use the
[db executeUpdateWithFormat:@"INSERT INTO myTable VALUES (%d)",42];
Internally, the
Using FMDatabaseQueue and Thread Safety.
Using a single instance of FMDatabase from multiple threads at onceis a bad idea. It has always been OK to make a FMDatabaseobjectper thread. Just don't share a single instanceacross threads, and definitely not across multiple threads at thesame time. Bad things will eventually happen and you'll eventuallyget something to crash, or maybe get an exception, or maybemeteorites will fall out of the sky and hit your MacPro.
So don't instantiate a single FMDatabase object and use itacross multiple threads.
Instead, use FMDatabaseQueue. It's your friend and it's here tohelp. Here's how to use it:
First, make your queue.
FMDatabaseQueue *queue = [FMDatabaseQueuedatabaseQueueWithPath:aPath];
Then use it like so:
[queue inDatabase:^(FMDatabase *db) {
}];
An easy way to wrap things up in a transaction can be done likethis:
[queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
}];
FMDatabaseQueue will make a serialized GCD queue in the backgroundand execute the blocks you pass to the GCD queue. This means if youcall your FMDatabaseQueue's methods from multiple threads at thesame time GDC will execute them in the order they are received.This means queries and updates won't step on each other's toes, andevery one is happy.
更多推荐
所有评论(0)