一丈莺、FMDB
項(xiàng)目:sqlite_useFMDB0414
(一)使用FMDB準(zhǔn)備工作:
1.導(dǎo)入sqlite3靜態(tài)庫
2.將fmdb拖入工程
3.在arc環(huán)境下趁矾,需要做以下修改:
4.導(dǎo)入FMDB.h
(二)使用FMDB庫操作數(shù)據(jù)庫
1.準(zhǔn)備工作
①導(dǎo)入sqlite3靜態(tài)庫
②將fmdb拖入工程
③導(dǎo)入FMDB.h
createTable/insert/update/delete:
1.創(chuàng)建數(shù)據(jù)庫對象(相當(dāng)于句柄)
2.打開數(shù)據(jù)庫
3.調(diào)用方法[_db executeUpdate:];
createTable/insert/update/delete
4.關(guān)閉數(shù)據(jù)庫
selecte:
1.創(chuàng)建數(shù)據(jù)庫對象(相當(dāng)于句柄)
2.打開數(shù)據(jù)庫
3.獲得結(jié)果集[_db executeQuery:];
4.從結(jié)果集中逐條查詢
5.關(guān)閉結(jié)果集/數(shù)據(jù)庫
源碼:
@interface ViewController ()
{
__weak IBOutlet UITextField *_nameTf;
__weak IBOutlet UITextField *_ageTf;
FMDatabase *_db;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//創(chuàng)建數(shù)據(jù)庫對象慷暂,用來操作數(shù)據(jù)庫文件(相當(dāng)于句柄)
_db = [[FMDatabase alloc]initWithPath:[self getFilePath]];
}
#pragma mark - **************** 獲取路徑
- (NSString *)getFilePath
{
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSLog(@"%@",path);
return [path stringByAppendingPathComponent:@"student.sqlite"];
}
#pragma mark - **************** 數(shù)據(jù)庫操作
//創(chuàng)建表
- (IBAction)createTable:(UIButton *)sender
{
//先打開數(shù)據(jù)庫
BOOL isOpen = [_db open];
if (isOpen)
{
//打開成功驹闰,創(chuàng)建表
//判斷表是否存在
BOOL isExist = [_db tableExists:@"student"];
if (isExist == NO)
{
//不存在表,創(chuàng)建
[_db executeUpdate:@"create table student(student_id integer primary key autoincrement not null,name text not null,age integer not null)"];
}
}
[_db close];
}
- (IBAction)insertClick:(UIButton *)sender
{
//1.打開數(shù)據(jù)庫
BOOL isOpen = [_db open];
if (isOpen == NO)
{
[_db close];
return;
}
[_db executeUpdateWithFormat:@"insert into student (name,age) values (%@,%d)",_nameTf.text,[_ageTf.text integerValue]];
[_db close];
}
- (IBAction)updateClick:(UIButton *)sender
{
BOOL isOpen = [_db open];
if (isOpen == NO)
{
[_db close];
return;
}
[_db executeUpdate:@"update student set age = 22 where student_id = 1"];
[_db close];
}
- (IBAction)deleteClick:(UIButton *)sender
{
BOOL isOpen = [_db open];
if (isOpen == NO)
{
[_db close];
return;
}
[_db executeUpdate:@"delete from student where age > 22"];
[_db close];
}
- (IBAction)selectClick:(UIButton *)sender
{
//1.打開數(shù)據(jù)庫
BOOL isOpen = [_db open];
if (isOpen == NO)
{
[_db close];
return;
}
//2.獲取結(jié)果集
FMResultSet *resultSet = [_db executeQuery:@"select name,age from student where student_id > 1"];
//3.從結(jié)果集中單步查詢
while ([resultSet next] == YES)
{
NSString *name = [resultSet stringForColumn:@"name"];
int age = [resultSet intForColumn:@"age"];
NSLog(@"%@:%d",name,age);
}
[resultSet close];
[_db close];
}
二皿桑、DAO(數(shù)據(jù)訪問對象)
項(xiàng)目:Database_DAO0414
DAO(Data Access Object) 數(shù)據(jù)訪問對象是第一個面向?qū)ο蟮臄?shù)據(jù)庫接口毫目,它顯露了 Microsoft Jet 數(shù)據(jù)庫引擎(由 Microsoft Access 所使用)蔬啡,并允許 Visual Basic 開發(fā)者通過 ODBC 像直接連接到其他數(shù)據(jù)庫一樣,直接連接到 Access 表镀虐。DAO 最適用于單系統(tǒng)應(yīng)用程序或小范圍本地分布使用箱蟆。