iOS-sqlite3&FMDB使用代码示范
数据库操作是我们使用十分频繁的一份操作,在iOS中如何使用数据库,使用什么数据库,是我们不得不考虑的一个问题。
小型数据我们可以使用plist文件,或者NSUserDefaults存储。数据量比较多得情况下,我们可以使用sqlite或者Core Data.
在此先介绍一下sqlite的系统API,然后介绍一下第三方库FMDB,使用第三方库比使用系统的sqlite简单方便。
对数据库的操作,我们可以简单理解为增删改查,下面的具体直接使用代码实现增删改查,不一具体介绍。
#import <UIKit/UIKit.h>
#import <sqlite3.h>
#import "Person.h"
@interface ViewController : UIViewController
{
NSMutableArray *_arrayData;
}
- (IBAction)addButtonClick:(id)sender;
- (IBAction)deleteButtonClick:(id)sender;
- (IBAction)updateButtonClick:(id)sender;
- (IBAction)selectButtonClick:(id)sender;
@end #import "ViewController.h" @interface ViewController () @end
sqlite3 *_database;
@implementation ViewController - (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_arrayData = [[NSMutableArray alloc]init];
for(int i = ;i < ;i ++)
{
Person *p = [[Person alloc]init];
p.name = [NSString stringWithFormat:@"wyg%d",i];
p.age = + i;
[_arrayData addObject:p];
}
[self createTable];
} - (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} - (IBAction)addButtonClick:(id)sender
{
[self insertData];
} - (IBAction)deleteButtonClick:(id)sender
{
[self deleteData];
} - (IBAction)updateButtonClick:(id)sender
{
[self updateData];
} - (IBAction)selectButtonClick:(id)sender
{
[self selectData];
} -(void)openDatabase
{
if (sqlite3_open([[self getFilePath] UTF8String], &_database) == SQLITE_OK)
{
NSLog(@"open success");
}
else
{
NSLog(@"open failed");
}
}
-(void)createTable
{
[self openDatabase];
NSString *sql = @"create table if not exists students(name text ,age integer)";
sqlite3_stmt *stmt = nil;
if (sqlite3_prepare_v2(_database, [sql UTF8String], -, &stmt, nil) == SQLITE_OK)
{
if (sqlite3_step(stmt) == SQLITE_DONE)
{
NSLog(@"create table success");
}
else
{
NSLog(@"create table failed");
}
}
sqlite3_finalize(stmt);
sqlite3_close(_database);
}
-(void)insertData
{
[self openDatabase];
NSString *sql = @"insert into students(name,age)values(?,?)";
sqlite3_stmt *stmt = nil;
for (int i = ; i < _arrayData.count; i ++)
{
Person *p = _arrayData[i];
if (sqlite3_prepare_v2(_database, [sql UTF8String], -, &stmt, nil) == SQLITE_OK)
{
sqlite3_bind_text(stmt, , [p.name UTF8String], strlen([p.name UTF8String]), nil);
sqlite3_bind_int(stmt, , p.age);
if (sqlite3_step(stmt) == SQLITE_DONE)
{
NSLog(@"insert success");
}
else
{
NSLog(@"insert failed");
}
}
}
sqlite3_finalize(stmt);
sqlite3_close(_database);
}
-(void)deleteData
{
[self openDatabase];
sqlite3_stmt *stmt = nil;
NSString *sql = @"delete from students where age > 23";
if (sqlite3_prepare_v2(_database, [sql UTF8String], -, &stmt, nil) == SQLITE_OK)
{
if (sqlite3_step(stmt) == SQLITE_DONE)
{
NSLog(@"delete success");
}
else
{
NSLog(@"delete failed");
}
}
sqlite3_finalize(stmt);
sqlite3_close(_database);
}
-(void)updateData
{
[self openDatabase];
sqlite3_stmt *stmt = nil;
NSString *sql = @"update students set name = 'www' where age > 22";
if (sqlite3_prepare_v2(_database, [sql UTF8String], -, &stmt, nil) == SQLITE_OK)
{
if (sqlite3_step(stmt) == SQLITE_DONE)
{
NSLog(@"update success");
}
else
{
NSLog(@"update failed");
}
}
sqlite3_finalize(stmt);
sqlite3_close(_database);
}
-(void)selectData
{
[self openDatabase];
NSString *sql = @"select *from students";
sqlite3_stmt *stmt = nil;
NSMutableArray *array = [[NSMutableArray alloc]init];
if (sqlite3_prepare_v2(_database, [sql UTF8String], -, &stmt, nil) == SQLITE_OK)
{
while (sqlite3_step(stmt) == SQLITE_ROW)
{
char *name = (char *)sqlite3_column_text(stmt, );
int age = sqlite3_column_int(stmt, );
Person *p = [[Person alloc]init];
p.name = [NSString stringWithUTF8String:name];
p.age = age;
[array addObject:p];
}
}
NSLog(@"---%@",array);
sqlite3_finalize(stmt);
sqlite3_close(_database);
}
-(NSString *)getFilePath
{
NSString *docuPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[];
NSString *filePath = [docuPath stringByAppendingPathComponent:@"database.db"];
return filePath;
}
@end
sqlite
关于FMDB,是对系统sqlite的封装,使用起来更加方便,我们可以从github上下载。
下面代码是对FMDB的基本封装。
其中包括对数据库打开关闭的操作,和数据库的基本操作。
对数据库创建,打开,关闭等操作我们封装在DatabaseTool类里面。
对数据库的基本操作,例如创建表,增删改查等操作,我们封装在ContactDAO类里面。
操作的数据我们封装在Contact里面。
*********************************************************
** DatabaseTool
** #import <Foundation/Foundation.h>
#import "FMDB.h"
@interface DatabaseTool : NSObject
+(FMDatabase *)shareDatabase;
+(BOOL)close;
@end #import "DatabaseTool.h"
static FMDatabase *_db = nil;
@implementation DatabaseTool
+(FMDatabase *)shareDatabase
{
if (_db == nil)
{
_db = [[FMDatabase alloc]initWithPath:[self getFilePath]];
}
[self open];
return _db;
}
+(NSString *)getFilePath
{
NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[];
NSString *path = [documentPath stringByAppendingPathComponent:@"file.db"];
return path;
}
+(BOOL)open
{
if ([_db open] == NO)
{
[_db close];
NSAssert(NO, @"数据库打开失败");
}
//设置数据库缓存机制
[_db setShouldCacheStatements:YES];
return YES;
}
+(BOOL)close
{
if ([_db close] == NO)
{
NSAssert(NO, @"数据库关闭失败");
}
return YES;
}
@end
*************************************************************
** Contact
**
#import <Foundation/Foundation.h>
//modal 模型
@interface Contact : NSObject
{
int _cid;
NSString *_name;
NSString *_phone;
}
@property(nonatomic,assign) int cid;
@property(nonatomic,copy) NSString *name;
@property(nonatomic,copy) NSString *phone;
//自定义初始化方法
-(id)initWithID:(int)ID name:(NSString *)aName phone:(NSString *)aPhone;
@end #import "Contact.h" @implementation Contact
@synthesize cid = _cid;
@synthesize name = _name;
@synthesize phone = _phone;
-(id)initWithID:(int)ID name:(NSString *)aName phone:(NSString *)aPhone
{
if (self = [super init])
{
self.cid = ID;
self.name = aName;
self.phone = aPhone;
}
return self;
}
-(void)dealloc
{
[_name release];
[_phone release];
[super dealloc];
}
@end
*************************************************************
** ContactDAO
**
#import <Foundation/Foundation.h>
#import "DatabaseTool.h"
//连接 数据模型和数据库对象 主要完成表的创建,增删改查得功能
@interface ContactDAO : NSObject
+(void)createContactTable;
+(void)insertData;
+(NSMutableArray *)queryData;
+(void)updateDataWithID:(int)cid;
+(void)deleteDataWithID:(int)cid;
@end #import "ContactDAO.h"
#import "Contact.h"
@implementation ContactDAO
+(void)createContactTable
{
FMDatabase *database = [DatabaseTool shareDatabase];
if ([database tableExists:@"contact"] == NO)
{
[database executeUpdate:@"create table contact(id integer primary key autoincrement not null,name text,phone text)"];
}
[DatabaseTool close];
}
+(void)insertData
{
FMDatabase *database = [DatabaseTool shareDatabase];
[database executeUpdate:@"insert into contact(name,phone)values(?,?)",@"wyg",@""];
[DatabaseTool close];
}
+(NSMutableArray *)queryData
{
NSMutableArray *array = [[NSMutableArray alloc]init];
FMDatabase *database = [DatabaseTool shareDatabase];
FMResultSet *set = [database executeQuery:@"select *from contact"];
while ([set next])
{
int cid = [set intForColumn:@"id"];
NSString *name = [set stringForColumn:@"name"];
NSString *phone = [set stringForColumn:@"phone"];
Contact *c = [[Contact alloc]initWithID:cid name:name phone:phone];
[array addObject:c];
[c release];
}
[set close];
[DatabaseTool close];
return array;
}
+(void)updateDataWithID:(int)cid
{
NSNumber *num = [NSNumber numberWithInt:cid];
FMDatabase *database = [DatabaseTool shareDatabase];
[database executeUpdate:@"update contact set name = 'www' where id = ?",num];
[DatabaseTool close];
}
+(void)deleteDataWithID:(int)cid
{
NSNumber *num = [NSNumber numberWithInt:cid];
FMDatabase *database = [DatabaseTool shareDatabase];
[database executeUpdate:@"delete from contact where id = ?",num];
[DatabaseTool close];
}
@end
FMDB
iOS-sqlite3&FMDB使用代码示范的更多相关文章
- IOS数据库FMDB增、删、改、查的使用【原创】
http://blog.it985.com/13588.html IOS数据库FMDB增.删.改.查的使用[原创] FMDB是一个XCODE的中一个轻量级的数据库,用于将网络资源存储在本地.所以,FM ...
- iOS sqlite3 的基本使用(增 删 改 查)
iOS sqlite3 的基本使用(增 删 改 查) 这篇博客不会讲述太多sql语言,目的重在实现sqlite3的一些基本操作. 例:增 删 改 查 如果想了解更多的sql语言可以利用强大的互联网. ...
- iOS——使用FMDB进行数据库操作(转载)
iOS 使用FMDB进行数据库操作 https://github.com/ccgus/fmdb [摘要]本文介绍iOS 使用FMDB进行数据库操作,并提供详细的示例代码供参考. FMDB 使用方法 A ...
- 关于AJAX 的交互模型、交互流程及代码示范
AJAX = 异步JavaScript + XML. 它是一种用于创建快速动态网页的技术.通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新.这意味着可以在不重新加载整个网页的情况 ...
- ios蓝牙开发(三)ios连接外设的代码实现:手机app去读写蓝牙设备。
手机app去读写蓝牙设备....... 代码下载: 原文博客主提供Github代码连接,地址是:https://github.com/coolnameismy/demo ios连接外设的代码实现流程: ...
- iOS 蓝牙开发(二)iOS 连接外设的代码实现(转)
转载自:http://www.cocoachina.com/ios/20150917/13456.html 原文作者:刘彦玮 上一篇文章介 绍了蓝牙的技术知识,这里我们具体说明一下中心模式的应用场景. ...
- iOS开发关于Block代码错误
本文永久地址为http://www.cnblogs.com/ChenYilong/p/4052362.html ,转载请注明出处. iOS开发关于Block代码错误 Incompatible bloc ...
- iOS书摘之编写高质量iOS与OS X代码的52个有效方法
来自<Effective Objective-C 2.0编写高质量iOS与OS X代码的52个有效方法>一书的摘要总结 一.熟悉Objective-C 了解Objective-C语言的起源 ...
- ios开发FMDB导入SQLCipher加密数据库
转:http://www.2cto.com/kf/201407/315727.html [iOS]FMDB/SQLCipher数据库加解密,迁移
随机推荐
- python基础一 day15 面试题
# def demo():# for i in range(4):# yield i## g=demo()## g1=(i for i in g)# g2=(i for i in g1)## prin ...
- MySQL 外键 表的查询
自增补充 这是查看怎么创建的表, \G示旋转90度显示表的内容 表的自增的关键是** AUTO_INCREMENT=3**,在表中添加数据后,这个会自动改变,通过alert可以改变这个默认值 mysq ...
- Logistic回归,梯度上升算法理论详解和实现
经过对Logistic回归理论的学习,推导出取对数后的似然函数为 现在我们的目的是求一个向量,使得最大.其中 对这个似然函数求偏导后得到 根据梯度上升算法有 进一步得到 我们可以初始化向量为0,或者随 ...
- JavaScript无提示关闭当前页面窗口,兼容IE/Firefox/Chrome
<script type="text/javascript" language="javascript"> function fc(){ var b ...
- Java字符串池(String Pool)深度解析(转)
出自 http://www.cnblogs.com/fangfuhai/p/5500065.html 在工作中,String类是我们使用频率非常高的一种对象类型.JVM为了提升性能和减少内存开销,避 ...
- matplotlib subplot 子图
总括 MATLAB和pyplot有当前的图形(figure)和当前的轴(axes)的概念,所有的作图命令都是对当前的对象作用.可以通过gca()获得当前的axes(轴),通过gcf()获得当前的图形( ...
- 【交互 细节题 思维题】cf1064E. Dwarves, Hats and Extrasensory Abilities
第一次做交互真有趣……:挺好的细节思维题 This is an interactive problem. In good old times dwarves tried to develop extr ...
- scipy学习之(二)——io操作及其misc操作对图片的处理
SciPy有许多模块.类和函数,io子模块可用于从各种文件格式中读取数据和将数据写入各种文件格式. from scipy import io import numpy as np 生成数据 data ...
- pandas中层次化索引与切片
Pandas层次化索引 1. 创建多层索引 隐式索引: 常见的方式是给dataframe构造函数的index参数传递两个或是多个数组 Series也可以创建多层索引 Series多层索引 B =Ser ...
- 13Shell脚本—编写简单脚本
1. 概述 Shell脚本命令的工作方式有两种:交互式和批处理. 交互式(Interrctive): 用户每输入一条命令就立即执行. 批处理(Batch): 由用户事先编写好一个完整的 Shell 脚 ...