首页 > 代码库 > IOS 操作数据库(FMDB)
IOS 操作数据库(FMDB)
公司最近在做离线缓存的东西,用的是sqlite数据库保存的。使用第三方类库FMDataBase对数据库进行相关操作,这是我写的一个小demo,废话不说,先上效果图:
在操作数据库的时候遇到了一点小问题,sqlite里面string类型就用text来存储,int型用integer,float用real,
需要注意的是:插入数据的时候如果string类型直接插入,但是要是float或者是integer类型就需要将插入值转化成NSNumber数据类型如下:[NSNumber numberWithInt:24]
在调试数据库操作的时候最好在模拟器上进行,然后打印出数据库路径,然后查看数据库里面的数据,是否存在,这里推荐一个查看sqlite数据库的软件,很小,功能不算强大但是也勉强够用了。(不要积分)
http://download.csdn.net/detail/zyzxrj/8203551
还需要注意一点,做数据库增删的时候不可查看数据库,这时候数据库会被锁住,导致插入或者删除失败。但是查询操作可以。
可参考下面语句
NSString *createMessageTable = @"create table if not exists message(messageNo integer primary key,failldReason text,contract text,contractPhone text,isRead integer, orderStatus integer, messageType integer, acceptMessageTime text,appointedTime text,orderDate text,startStation text,arrivalStation text,transportLocation text,tradeNo text) ";
这个界面我为了省时间直接xib拖得,相信有一定ios开发基础的人都可以用代码写出来,我也不废话了,主要说一些数据库操作的问题:
DataBaseViewController.h:
#import <UIKit/UIKit.h> @interface DataBaseViewController : UIViewController @property (weak, nonatomic) IBOutlet UITextField *nameTextField; @property (weak, nonatomic) IBOutlet UITextField *sexTextField; @property (weak, nonatomic) IBOutlet UITextField *ageTextField; - (IBAction)save:(id)sender; - (IBAction)query:(id)sender; - (IBAction)queryByCondition:(id)sender; - (IBAction)update:(id)sender; - (IBAction)deleteByCondition:(id)sender; @end
DataBaseViewController.m:
// // DataBaseViewController.m // Location // // Created by admin on 14-11-17. // Copyright (c) 2014年 admin. All rights reserved. // #import "DataBaseViewController.h" #import "FMDatabase.h" #import "FMDatabaseQueue.h" #define IOS7_OR_LATER ([[[UIDevice currentDevice] systemVersion]floatValue] >= 7.0) @interface DataBaseViewController () @end @implementation DataBaseViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; //控制器,点击空白地方,隐藏键盘 CGRect cgrect = self.view.frame; if (!IOS7_OR_LATER) { cgrect.origin.y -= 20; } UIControl *clickControl = [[UIControl alloc] init]; clickControl.frame = cgrect; [clickControl addTarget:self action:@selector(hideKeyboard) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:clickControl]; [self.view sendSubviewToBack:clickControl]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } //隐藏软键盘 - (void)hideKeyboard { [_nameTextField resignFirstResponder]; [_ageTextField resignFirstResponder]; [_sexTextField resignFirstResponder]; } - (IBAction)save:(id)sender { //获取Document文件夹下的数据库文件,没有则创建 NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *dbPath = [docPath stringByAppendingPathComponent:@"user.db"]; NSLog(@"%@",dbPath); //获取数据库并打开 FMDatabase *dataBase = [FMDatabase databaseWithPath:dbPath]; if (![dataBase open]) { NSLog(@"打开数据库失败"); return ; } //创建表(FMDB中只有update和query操作,出了查询其他都是update操作) [dataBase executeUpdate:@"create table if not exists user(name text,gender text,age integer) "]; //插入数据 BOOL inser = [dataBase executeUpdate:@"insert into user values(?,?,?)",_nameTextField.text,_sexTextField.text,_ageTextField.text]; if (inser) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"信息保存成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil]; [alert show]; } [dataBase close]; } //查询全部 - (IBAction)query:(id)sender { NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *dbPath = [docPath stringByAppendingPathComponent:@"user.db"]; FMDatabase *dataBase = [FMDatabase databaseWithPath:dbPath]; if (![dataBase open]) { NSLog(@"打开数据库失败"); return ; } FMResultSet *resultSet = [dataBase executeQuery:@"select * from user"]; while ([resultSet next]) { NSString *name = [resultSet stringForColumn:@"name"]; NSString *genter = [resultSet stringForColumn:@"gender"]; int age = [resultSet intForColumn:@"age"]; NSLog(@"Name:%@,Gender:%@,Age:%d",name,genter,age); } [dataBase close]; } //条件查询 - (IBAction)queryByCondition:(id)sender { NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *dbPath = [docPath stringByAppendingPathComponent:@"user.db"]; FMDatabase *dataBase = [FMDatabase databaseWithPath:dbPath]; if (![dataBase open]) { return ; } // FMResultSet *resultSet = [dataBase executeQuery:@"select *from user where name = ?",@"ZY"]; FMResultSet *resultSet = [dataBase executeQueryWithFormat:@"select * from user where name = %@",@"zy"]; while ([resultSet next]) { NSString *name = [resultSet stringForColumnIndex:0]; NSString *gender = [resultSet stringForColumn:@"gender"]; int age = [resultSet intForColumn:@"age"]; NSLog(@"Name:%@,Gender:%@,Age:%d",name,gender,age); } [dataBase close]; } - (IBAction)update:(id)sender { NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *dbPath = [docPath stringByAppendingPathComponent:@"user.db"]; FMDatabase *dataBase = [FMDatabase databaseWithPath:dbPath]; if (![dataBase open]) { return ; } //参数必须是NSObject的子类,int,double,bool这种基本类型,需要封装成对应的包装类才可以 BOOL update = [dataBase executeUpdate:@"update user set age = ? where name = ?",[NSNumber numberWithInt:24],@"ZY"]; if (update) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"信息更新成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil]; [alert show]; } [dataBase close]; } - (IBAction)deleteByCondition:(id)sender { NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *dbPath = [docPath stringByAppendingPathComponent:@"user.db"]; FMDatabase *dataBase = [FMDatabase databaseWithPath:dbPath]; if (![dataBase open]) { return ; } BOOL delete = [dataBase executeUpdateWithFormat:@"delete from user where name = %@",@"zy"]; if (delete) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"信息删除成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil]; [alert show]; } [dataBase close]; } @end下面是整个demo的源文件(不要积分的):
http://download.csdn.net/detail/zyzxrj/8203583
大家要是有不解之处可以参考代码
IOS 操作数据库(FMDB)