iphone数据库(sqlite3)的用法操作
首先你在用之前要在项目中加入libsqlite3.dylib
1、定义模型
[cpp] #import <Foundation/Foundation.h>
#import "sqlite3.h"
@class NotePad;
@class NoteDb;
@inte易做图ce NoteSqlite : NSObject{
sqlite3 *database;
sqlite3_stmt *statement;
char *errorMsg;
}
//打开数据库
-(BOOL)open;
//创建青
-(BOOL)create;
//增加、删除、修改、查询
-(BOOL)insert:(NotePad*)aNote;
-(BOOL)deleteALLNote;
-(BOOL)deleteaNote:(NotePad*)aNote;
-(BOOL)update:(NotePad*)aNote;
-(NoteDb*)selecteAll;
-(NoteDb*)selectNotes:(NotePad*)aNote;
@end
#import <Foundation/Foundation.h>
#import "sqlite3.h"
@class NotePad;
@class NoteDb;
@inte易做图ce NoteSqlite : NSObject{
sqlite3 *database;
sqlite3_stmt *statement;
char *errorMsg;
}
//打开数据库
-(BOOL)open;
//创建青
-(BOOL)create;
//增加、删除、修改、查询
-(BOOL)insert:(NotePad*)aNote;
-(BOOL)deleteALLNote;
-(BOOL)deleteaNote:(NotePad*)aNote;
-(BOOL)update:(NotePad*)aNote;
-(NoteDb*)selecteAll;
-(NoteDb*)selectNotes:(NotePad*)aNote;
@end
2、实现方法
[cpp] #import "NoteSqlite.h"
#import "NotePad.h"
#import "NoteDb.h"
@implementation NoteSqlite
-(id)init{
self=[super init];
return self;
}
//打开数据库
-(BOOL)open{
NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"noteList.db"];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL find = [fileManager fileExistsAtPath:path];
//判断文件是否存在
if (find) {
NSLog(@"数据库文件已经存在");
//打开数据库、返回操作是否正确
if(sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
NSLog(@"打开成功数据库");
}
return YES;
}else{
if(sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
//调用createMusicList创建数据库和表
[self create];
return YES;
} else {
sqlite3_close(database);
NSLog(@"Error: open database file.");
return NO;
}
return NO;
}
}
//创建表
-(BOOL)create{
//创建表语句
const char *createSql="create table if not exists note (id integer primary key autoincrement,theme text,information text,ndate text,priority integer)";
//创建表是否成功
if (sqlite3_exec(database, createSql, NULL, NULL, &errorMsg)==SQLITE_OK) {
NSLog(@"create ok.");
return YES;
}else{
//打印出错信息
NSLog(@"error: %s",errorMsg);
sqlite3_free(errorMsg);
}
return NO;
}
//增加、删除、修改、查询
-(BOOL)insert:(NotePad*)aNote{
//向表中插入记录
//定义一个sql语句
NSString *insertStatementNS = [NSString stringWithFormat:
@"insert into \"note\"\
(theme, information, ndate,priority)\
values (\"%@\", \"%@\", \"%@\",%d)",
aNote.theme,aNote.information,[NSString stringWithFormat:@"%@",aNote.ndate],aNote.priority
];
//将定义的NSString的sql语句,转换成UTF8的c风格的字符串
const char *insertSql = [insertStatementNS UTF8String];
//执行插入语句
if (sqlite3_exec(database, insertSql, NULL, NULL, &errorMsg)==SQLITE_OK) {
NSLog(@"insert ok.");
return YES;
}else{
NSLog(@"error: %s",errorMsg);
sqlite3_free(errorMsg);
}
return NO;
}
-(BOOL)deleteALLNote{
//删除所有数据,条件为1>0永真
const char
补充:移动开发 , IOS ,