类库文件添加完毕后,到这一步工程就应该可以正常编译了。如果到这一步你的工程还有错误,那就恭喜你自己在好好检查检查工程的结构啦。接下来将步入正题,老规矩还是以一个实例的形式向大家介绍如何使用FMDB。
首先,在ViewController.h文件
#import <UIKit/UIKit.h>
#import "FMDatabase.h"
@interface ViewController : UIViewController
@property (strong, nonatomic) FMDatabase* db;
-(IBAction)createTable;
-(IBAction)insertData;
-(IBAction)queryTable;
-(IBAction)updateTable;
-(IBAction)deleteTable;
@end
之后是:ViewController.m
- (void)viewDidLoad
{
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentDirectory = [paths objectAtIndex:0];
NSString* dbPath = [documentDirectory stringByAppendingPathComponent:@"Test.db"];
NSLog(@"%@",dbPath);
self.db = [FMDatabasedatabaseWithPath:dbPath];
if ([self.dbopen]) {
}
else
{
return;
}
}
//创建
-(IBAction)createTable
{
[self.dbexecuteUpdate:@"CREATE TABLE Customer (Name text,Age integer)"];
}
//插入
-(IBAction)insertData
{
[self.dbexecuteUpdate:@"INSERT INTO Customer (Name,Age) VALUES (?,?)",@"叫什么呢",[NSNumber numberWithInt:20]];
}
//查找
-(IBAction)queryTable
{
FMResultSet* queryResulte = [self.dbexecuteQuery:@"SELECT * FROM Customer"];
while ([queryResulte next])
{
NSLog(@"%@:%@",[queryResulte stringForColumn:@"Name"],[queryResulte stringForColumn:@"Age"]);
}
[queryResulte close];
}
//更新
-(IBAction)updateTable
{
//将“叫什么呢”这个名字改成@"不知道"
[self.dbexecuteUpdate:@"UPDATE Customer SET Name = ? WHERE Name = ?",@"不知道",@"叫什么呢"];
}
//删除
-(IBAction)deleteTable
{
//根据名字删除
[self.dbexecuteUpdate:@"DELETE FROM Customer WHERE Name = ?",@"不知道"];
}
下载地址: