OC的SQLite可参考的方法

本文介绍了一个用于操作SQLite数据库的Objective-C封装类,包括创建表、插入数据、删除数据、修改数据及查询数据的方法,并提供了具体的使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看别人的代码,觉得有些代码封装得不错,所以保留下来,希望有帮助。

操作数据库的接口部分:

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

@interface BaseDB : NSObject
//创建表
- (void)createTable:(NSString *)sql;
/**
 * 接口描述:插入数据、删除数据、修改数据
 * 参数:  sql: SQL语句
 * 返回值:是否执行成功 *
 */
- (BOOL)dealData:(NSString *)sql paramsarray:(NSArray *)params;

/**
 *  接口描述:查询数据
 *  参数:  sql:SQL语句
 *  返回值:[
                [“字段值1”,“字段值2”,“字段值3”],
                [“字段值1”,“字段值2”,“字段值3”],
                [“字段值1”,“字段值2”,“字段值3”], 
           ]
 */
- (NSMutableArray *)selectData:(NSString *)sql columns:(int)number;
@end

 

每个接口的实现部分:

#import "BaseDB.h"
#define kFilename  @"data.sqlite"
@implementation BaseDB
- (NSString *)filePath {
    NSString *filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",kFilename];
    return filePath;
}
- (void)createTable:(NSString *)sql {
    sqlite3 *sqlite = nil;
    //打开数据库
    if (sqlite3_open([self.filePath UTF8String], &sqlite) != SQLITE_OK) {
        NSLog(@"打开数据库失败");
        sqlite3_close(sqlite);
        return;
    }
    
    //执行创建表SQL语句
    char *errmsg = nil;
    if (sqlite3_exec(sqlite, [sql UTF8String], NULL, NULL, &errmsg) != SQLITE_OK) {
        NSLog(@"创建表失败:%s",errmsg);
        sqlite3_close(sqlite);
    }
    //关闭数据库
    sqlite3_close(sqlite);   
}

/**
 * 接口描述:插入数据、删除数据、修改数据
 * 参数:  sql: SQL语句
 * 返回值:是否执行成功 *
 */
// INSERT INTO User(username,password,email) values(?,?,?)
- (BOOL)dealData:(NSString *)sql paramsarray:(NSArray *)params {
    sqlite3 *sqlite = nil;
    sqlite3_stmt *stmt = nil;    
    //打开数据库
    if (sqlite3_open([self.filePath UTF8String], &sqlite) != SQLITE_OK) {
        NSLog(@"打开数据库失败");
        sqlite3_close(sqlite);
        return NO;
    }
    
    //编译SQL语句
    if (sqlite3_prepare_v2(sqlite, [sql UTF8String], -1, &stmt, NULL) != SQLITE_OK) {
        NSLog(@"SQL语句编译失败");
        sqlite3_close(sqlite);
        return NO;
    }
    
    //绑定数据
    for (int i=0; i<params.count; i++) {
        NSString *value = [params objectAtIndex:i];
        sqlite3_bind_text(stmt, i+1, [value UTF8String], -1, NULL);
    }

    //执行SQL语句
    if(sqlite3_step(stmt) == SQLITE_ERROR) {
        NSLog(@"SQL语句执行失败");
        sqlite3_close(sqlite);
        return NO;        
    }

    //关闭数据库
    sqlite3_finalize(stmt);
    sqlite3_close(sqlite);
    return YES;
}

/**
 *  接口描述:查询数据
 *  参数:  sql:SQL语句
 *  返回值:[
    [“字段值1”,“字段值2”,“字段值3”],
    [“字段值1”,“字段值2”,“字段值3”],
    [“字段值1”,“字段值2”,“字段值3”],
  ]
 */
//SELECT username,password,email FROM User
- (NSMutableArray *)selectData:(NSString *)sql columns:(int)number {
    sqlite3 *sqlite = nil;
    sqlite3_stmt *stmt = nil;
    
    //打开数据库
    if (sqlite3_open([self.filePath UTF8String], &sqlite) != SQLITE_OK) {
        NSLog(@"打开数据库失败");
        sqlite3_close(sqlite);
        return NO;
    }
    
    //编译SQL语句
    if (sqlite3_prepare_v2(sqlite, [sql UTF8String], -1, &stmt, NULL) != SQLITE_OK) {
        NSLog(@"SQL语句编译失败");
        sqlite3_close(sqlite);
        return NO;
    }
    
    //查询数据
    int result = sqlite3_step(stmt);
    NSMutableArray *data = [NSMutableArray array];
    while (result == SQLITE_ROW) {
        NSMutableArray *row = [NSMutableArray arrayWithCapacity:3];
        for (int i=0; i<number; i++) {
            char *columnText = (char *)sqlite3_column_text(stmt, i);
            NSString *string = [NSString stringWithCString:columnText encoding:NSUTF8StringEncoding];
            [row addObject:string];
        }
        [data addObject:row];        
        result = sqlite3_step(stmt);
    }

    //关闭数据库
    sqlite3_finalize(stmt);
    sqlite3_close(sqlite);
    return data;
}
@end 

 

 如何使用这些接口呢?

具体例子:

#import "UserDB.h"
static UserDB *instnce;
@implementation UserDB
+ (id)shareInstance {/*单例模式*/
    if (instnce == nil) {
        instnce = [[[self class] alloc] init];
    }
    return instnce;
}

- (void)createTable {
    NSString *sql = @"CREATE TABLE IF NOT EXISTS User (username TEXT primary key,password TEXT,age TEXT);";
    [self createTable:sql];
}

- (BOOL)addUser:(UserModel *)userModel {
    NSString *sql = @"INSERT OR REPLACE INTO User (username,password,age) VALUES (?,?,?)";
    NSArray *params = [NSArray arrayWithObjects:userModel.username,
                                                userModel.password,
                                                userModel.age, nil];    
    return [self dealData:sql paramsarray:params];
}

- (NSArray *)findUsers {
    NSString *sql = @"SELECT username,password,age FROM User";
    NSArray *data = [self selectData:sql columns:3];
    NSMutableArray *users = [NSMutableArray array];
    for (NSArray *row in data) {
        NSString *username = [row objectAtIndex:0];
        NSString *password = [row objectAtIndex:1];
        NSString *age = [row objectAtIndex:2];        
        UserModel *user = [[UserModel alloc] init];
        user.username = username;
        user.password = password;
        user.age = age;
        [users addObject:user];
        [user release];
    }    
    return users;
}

@end

 

 

 

### iOS Objective-C 开发商城应用教程 Objective-C 是一种面向对象的编程语言,专为 iOS 和 macOS 平台设计,融合了 C 语言和 Smalltalk 的特性[^1]。在开发 iOS 商城应用时,Objective-C 提供了丰富的类库和框架支持,例如 UIKit、Core Data 等,这些工具可以帮助开发者构建功能完善的移动应用。 #### 1. 基础知识 在开始开发商城应用之前,需要熟悉 Objective-C 的核心概念,包括类和对象、消息传递以及内存管理等。同时,了解如何使用 Xcode 构建项目也是非常重要的。以下是一个简单的 Hello World 示例,展示了如何设置一个基础的 iOS 项目: ```objc #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { NSLog(@"Hello, World!"); } return 0; } ``` #### 2. 商城应用的关键模块 开发商城应用通常涉及以下几个关键模块: - **用户界面 (UI)**:使用 UIKit 或 Storyboard 创建应用程序的界面。熟悉 UITableView 和 UICollectionView 是非常重要的,因为它们常用于展示商品列表和分类。 - **网络请求**:通过 NSURLSession 或第三方库(如 AFNetworking)实现与服务器的交互,获取商品数据、用户信息等[^2]。 - **数据存储**:可以使用 Core Data 或 SQLite 存储本地数据,例如购物车内容或用户偏好。 - **支付集成**:集成 Apple Pay 或其他支付 SDK,以支持在线支付功能。 - **蓝牙功能(可选)**:如果需要与外部设备通信,可以参考蓝牙开发教程[^3]。 #### 3. 推荐学习资源 以下是几个推荐的学习资源,帮助开发者掌握 Objective-C 和 iOS 商城应用开发的相关技能: - [从零开始的 iOS 开发之旅:Objective-C 篇(上)][^1] - [Objective-C 入门教程][^2] - [iOS 开发~向沙盒中写入文件、文件夹以及从沙盒中读取文件][^3] #### 4. 示例代码 以下是一个简单的示例,展示如何通过网络请求获取商品数据并将其显示在表格视图中: ```objc #import <UIKit/UIKit.h> @interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> @property (nonatomic, strong) NSArray *products; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 模拟网络请求 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSString *urlString = @"https://example.com/api/products"; NSURL *url = [NSURL URLWithString:urlString]; NSData *data = [NSData dataWithContentsOfURL:url]; if (data) { NSError *error = nil; NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; if (!error) { self.products = jsonArray; dispatch_async(dispatch_get_main_queue(), ^{ [self.tableView reloadData]; }); } } }); } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.products.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"ProductCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier]; } NSDictionary *product = self.products[indexPath.row]; cell.textLabel.text = product[@"name"]; cell.detailTextLabel.text = [NSString stringWithFormat:@"$%.2f", [product[@"price"] floatValue]]; return cell; } @end ``` ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值