关闭

iPhone开发之SQLite的使用

标签: sqliteiphonedatabasesqlstring数据库
638人阅读 评论(0) 收藏 举报
分类:

SQLite确实是个好东西,不需要引擎,啥程序都可以使用,特别在嵌入式开发中使用得特别多。

记得刚开始在iPhone中使用SQLite的时候,琢磨了几天,才完成增删改查,费了九牛二虎之力呀。

iPhone中使用SQLite其实也不算简单,链接数据库、执行SQL,都感觉挺复杂的。经过多番研究,将iPhone中SQLite的使用方法封装到一个类中了,增删改查使用起来都极其方便,已经在多个项目中使用了我封装的这个类,目前还没发现有啥bug。

SQLiteOperation.h

#import <Foundation/Foundation.h>
#import <sqlite3.h>
#import <CoreLocation/CoreLocation.h>

@interface SQLiteOperation : NSObject {
    sqlite3 *database;
    NSString *path;
}

- (void)readyDatabse;
- (void)getPath;
- (NSMutableArray *)selectData:(NSString *)sql resultColumns:(int)col;
- (BOOL)dealData:(NSString *)sql paramArray:(NSArray *)param;

@end

SQLiteOperation.m

#import "SQLiteOperation.h"

@implementation SQLiteOperation

#pragma mark 准备数据库
- (void)readyDatabse {
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"test.sqlite"];
    success = [fileManager fileExistsAtPath:writableDBPath];
    [self getPath];
    if (success) return;
    // The writable database does not exist, so copy the default to the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"test.sqlite"];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    if (!success) {
        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
}

#pragma mark 路径
- (void)getPath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    path = [documentsDirectory stringByAppendingPathComponent:@"test.sqlite"];
}

#pragma mark 查询数据库
/************
 sql:sql语句
 col:sql语句需要操作的表的所有字段数
 ***********/
- (NSMutableArray *)selectData:(NSString *)sql resultColumns:(int)col {
    [self readyDatabse];
    NSMutableArray *returnArray = [[[NSMutableArray alloc] init] autorelease];//所有记录
    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
        sqlite3_stmt *statement = nil;
        if (sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL) == SQLITE_OK) {
            while (sqlite3_step(statement) == SQLITE_ROW) {
                NSMutableArray *row = [[NSMutableArray alloc] init];//一条记录
                //NSLog(@"=====%@",statement);
                for(int i=0; i<col; i++){
                    [row addObject:[NSString stringWithFormat:@"%s", sqlite3_column_text(statement, i)]];
                }
                [returnArray addObject:row];
                [row release];
            }//end while
        }else {
            NSLog(@"Error: failed to prepare");
            return NO;
        }//end if
        //NSLog(@"returnArray:%@",returnArray);
        return returnArray;
        sqlite3_finalize(statement);
    } else {
        sqlite3_close(database);
        NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
    }//end if
    sqlite3_close(database);
    return returnArray;
}

#pragma mark 增,删,改数据库
/************
 sql:sql语句
 param:sql语句中?对应的值组成的数组
 ***********/
- (BOOL)dealData:(NSString *)sql paramArray:(NSArray *)param {
    [self readyDatabse];
    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
        sqlite3_stmt *statement = nil;
        int success = sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL);
        if (success != SQLITE_OK) {
            NSLog(@"Error: failed to prepare");
            return NO;
        }
        //绑定参数
        NSInteger max = [param count];
        for (int i=0; i<max; i++) {
            NSString *temp = [param objectAtIndex:i];
            sqlite3_bind_text(statement, i+1, [temp UTF8String], -1, SQLITE_TRANSIENT);
        }
        success = sqlite3_step(statement);
        sqlite3_finalize(statement);
        if (success == SQLITE_ERROR) {
            NSLog(@"Error: failed to insert into the database");
            return NO;
        }
    }
    sqlite3_close(database);
    NSLog(@"dealData 成功");
    return TRUE;
}

- (void)dealloc{
    [path release];
    [super dealloc];
}

@end

在此类中将查询写成了一个方法,增、删、改写成了一个方法。

调用起来都灰常简单:


增
NSArray *paramarray = [[NSArray alloc] initWithObjects:@"Miles", @"28", @"69", nil];
NSString *sql = [[NSString alloc] initWithString:@"INSERT INTO t_test (name, age, score) VALUES (?, ?, ?)"];
[self dealData:sql paramArray:paramarray];
[paramarray release];
[sql release];

删
NSArray *paramarray = [[NSArray alloc] initWithObjects:@"2", nil];
NSString *sql = [[NSString alloc] initWithString:@"DELETE FROM t_test WHERE id=?"];
[self dealData:sql paramArray:paramarray];
[paramarray release];
[sql release];

改
NSArray *paramarray = [[NSArray alloc] initWithObjects:@"Miles", @"30", @"2", nil];
NSString *sql = [[NSString alloc] initWithString:@"UPDATE t_test SET name=?, age=? WHERE id=?"];
[self dealData:sql paramArray:paramarray];
[paramarray release];
[sql release];

查
NSString *sql = [[NSString alloc] initWithString:@"SELECT * FROM t_test WHERE score>0"];
[self selectData:sql resultColumns:4];
[paramarray release];
[sql release];


点击打开链接 demo


http://download.csdn.net/detail/ydj213/4163700


本站原创,转载请标明:来自追梦博客(http://www.wuleilei.com/)

本文地址:http://www.wuleilei.com/Blog/240



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:372445次
    • 积分:4754
    • 等级:
    • 排名:第6320名
    • 原创:52篇
    • 转载:277篇
    • 译文:2篇
    • 评论:32条