数据库封装

#import <Foundation/Foundation.h>

#import "Student.h"

#import <sqlite3.h>

 

@interface SqliteManager : NSObject

{

    sqlite3 *db;

 

}

-(void) open;

-(void) insertStudent:(Student *) s;

-(void) updateStudent:(Student *) s;

-(void) deleteStudent:(Student *) s;

-(NSArray *) searchStudent:(Student *) s;

-(void) close;

 

@end

 

 

#import "SqliteManager.h"

 

@implementation SqliteManager

 

-(void) open;

{

    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/student.sqlite"];

    

     //打开数据库文件  第一个参数代表数据库文件的路径,注意需要调用UTF8String方法将NSString转换成c的字符串格式,第二个参数代表数据库对象。该方法如果返回0,代表数据库打开成功,如果该路径没有数据库文件,则先创建再打开,否则直接打开

    int a = sqlite3_open([path UTF8String], &db);

    if (a == 0) {

        [self createTable];

    }

}

 

 //创建数据库表

-(void) createTable

{

   NSString *s = @"create table if not exists Student(name TEXT)";

    [self execSql:s ];

 

}

-(void)execSql :(NSString *) str

{

   sqlite3_exec(db, [str  UTF8String], NULL, NULL, NULL);

}

-(void) insertStudent:(Student *) s

{

    //数据库增加数据

    //sql插入语句:insert into Student(表名) (要进行保存的字段名,名字之间用逗号隔开) values(要保存的实际数据,多个数据用逗号隔开,注意:此处数据要与前面的字段名保持一致,且如果是TEXT类型,需要用单引号引起来)

    NSString *sql = [NSStringstringWithFormat:@"insert into Student (name) values('%@')",s.name];

    [self execSql:sql];

 

}

 

//搜索

-(NSArray *) searchStudent:(Student *) s

{

    NSMutableArray *arr = [NSMutableArrayarray];

    

    NSString *sql = nil;

    if ([SqliteManager isBlankString:s]) {

        sql = @"select * from Student";

    }else{

        sql = [NSStringstringWithFormat: @"select * from Student where name = '%@'",s];

    }

    

    sqlite3_stmt *_stmt = nil;

    

    int res = sqlite3_prepare(db, [sql UTF8String], -1, &_stmt, NULL);

    if (res == 0) {

        while (SQLITE_ROW == sqlite3_step(_stmt)) {

            const unsigned char *name = sqlite3_column_text(_stmt, 0);

            Student *s = [[Student alloc] init];

            s.name = [NSString stringWithUTF8String:(const char *)name];

            [arr addObject:s];

        }

    }

    

    return arr;

 

}

+ (BOOL)isBlankString:(NSString *)string{

    

    if (string == nil) {

        return YES;

    }

    if (string == NULL) {

        return YES;

    }

    if ([string isKindOfClass:[NSNull class]]) {

        return YES;

    }

    if (string.length == 0) {

        return YES;

    }

    returnNO;

}

-(void) close

{

 sqlite3_close(db);

}

 

@end

原文地址:https://www.cnblogs.com/lcl15/p/5011292.html