IOS之数据库的查找,删除,添加,更新
2012-11-21 14:03:36 来源:WEB开发网 DB类之.h文件
#import <Foundation/Foundation.h>
#import <sqlite3.h>
@interface DB : NSObject
+(sqlite3 *)openDB;//打开数据库
-(void)closeDB;//关闭数据库
@end
DB类之.m文件
#import "DB.h"
#import <sqlite3.h>
static sqlite3 *db = nil;
@implementation DB
+(sqlite3 *)openDB
{
if(db)
{
return db;
}
//目标路径
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES)objectAtIndex:0];
//原始路径
NSString *filePath = [docPath stringByAppendingPathComponent:@"db.sqlite"];
NSFileManager *fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:filePath] == NO)//如果doc下没有数据库,从bundle里面拷贝过来
{
NSString *bundle = [[NSBundle mainBundle]pathForResource:@"classDB" ofType:@"sqlite"];
NSError *err = nil;
if ([fm copyItemAtPath:bundle toPath:filePath error:&err] == NO) //如果拷贝失败
{
NSLog(@"%@",[err localizedDescription]);
}
}
sqlite3_open([filePath UTF8String], &db);
return db;
}
-(void)closeDB
{
if (db)
{
sqlite3_close(db);
}
}
@end
Person类.h文件
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property(nonatomic,retain)NSString *name,*phone;
@property(nonatomic,assign)int age,ID;
-(id)initWithName:(NSString *)name phone:(NSString *)phone age:(int)age ID:(int)ID;
+(NSMutableArray *)findAll;
+(int)count;
+(Person *)findByID:(int)ID;
+(NSMutableArray *)findByname:(NSString *)name;
+(void)addName:(NSString *)name phone:(NSString *)phone age:(int)age;
+(void)deleteByID:(int)ID;
+(void)updataName:(NSString *)name phone:(NSString *)phone age:(int)age forID:(int)ID;
@end
Person类.m文件
#import "Person.h"
#import "DB.h"
@implementation Person
@synthesize name,ID,phone,age;
-(id)initWithName:(NSString *)aName phone:(NSString *)aPhone age:(int)aAge ID:(int)aID
{
[super init];
if (self)
{
self.name = aName;
self.phone = aPhone;
self.age = aAge;
self.ID = aID;
}
return self;
}
-(NSString *)description
{
return [NSString stringWithFormat:@"id = %d name = %@ phone = %@ age = %d",self.ID,self.name,self.phone,self.age ];
}
+(NSMutableArray *)findAll
{
sqlite3 *db = [DB openDB];
sqlite3_stmt *stmt = nil;//创建一个声明对象
int result = sqlite3_prepare_v2(db, "select * from classDB order by ID ", -1, &stmt, nil);
NSMutableArray *persons = nil;
if (result == SQLITE_OK)
{
persons = [[NSMutableArray alloc]init];
while (sqlite3_step(stmt) == SQLITE_ROW)
{
int ID = sqlite3_column_int(stmt, 0);
const unsigned char *name = sqlite3_column_text(stmt, 1);
更多精彩
赞助商链接