第六十六篇、OC_Sqlite数据库操作

#import <Foundation/Foundation.h>
#import <sqlite3.h>
#define kFilename   @"data.sqlite"

@interface SQLService:NSObject
{
    NSMutableArray *FSQLExecutioResultsMutableArray;    //SQL运行结果
    NSString *FErrorString;     //错误信息
    NSString *FDatabaseAddressString;       //数据库文件存放地址
}

@property (nonatomic) sqlite3 *FDatabaseSqlite;

- (void)SetDatabaseAddressString:(NSString *)ANewString;
- (NSString *)GetErrorString;
- (NSMutableArray *)GetSQLExecutioResultsMutableArray;

//- (BOOL)ExecuteSQL:(NSString *)ASQLString;
- (BOOL)CreateTable:(NSString *)ASQLString;
- (BOOL)InsertData:(NSString *)ASQLString;
- (BOOL)DeleteData:(NSString *)ASQLString;
- (BOOL)UpdateData:(NSString *)ASQLString;
- (BOOL)SelectData:(NSString *)ASQLString;
- (BOOL)SelectAllData:(NSString *)ASQLString;
- (BOOL)DropTable:(NSString *)ASQLString;
@end
#import "SQLService.h"
#define kLibrary [NSHomeDirectory() stringByAppendingPathComponent:@"Library"]
@interface SQLService ()

- (void)SetErrorString:(NSString *)ANewString;
- (void)SetSQLExecutioResultsMutableArray:(NSMutableArray *)ANewMutableArray;
- (NSString *)GetDatabaseAddressString;

- (NSString *)DataFilePath;
- (BOOL)OpenDataBase;

- (BOOL)CreateTable:(NSString *)ASQLString;
@end

@implementation SQLService
@synthesize FDatabaseSqlite;

- (id)init
{
    if (![self GetSQLExecutioResultsMutableArray]) {
        NSMutableArray *ASQLExecutioResultsMutableArray = [[NSMutableArray alloc] initWithCapacity:1];
        [self SetSQLExecutioResultsMutableArray:ASQLExecutioResultsMutableArray];
        [ASQLExecutioResultsMutableArray release];
    }
    if (![self GetErrorString]) {
        NSString *AErrorString = [[NSString alloc] init];
        [self SetErrorString:AErrorString];
        [AErrorString release];
    }
    return self;
}

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

- (void)SetDatabaseAddressString:(NSString *)ANewString
{
    FDatabaseAddressString = [ANewString retain];
}
- (NSString *)GetDatabaseAddressString
{
    return FDatabaseAddressString;
}
- (void)SetErrorString:(NSString *)ANewString
{
    if (FErrorString != ANewString) {
        [FErrorString release];
        FErrorString = [ANewString retain];
    }
}
- (NSString *)GetErrorString
{
    return FErrorString;
}
- (void)SetSQLExecutioResultsMutableArray:(NSMutableArray *)ANewMutableArray
{
    if (FSQLExecutioResultsMutableArray != ANewMutableArray) {
        [FSQLExecutioResultsMutableArray release];
        FSQLExecutioResultsMutableArray = [ANewMutableArray retain];
    }
}
- (NSMutableArray *)GetSQLExecutioResultsMutableArray
{
    return FSQLExecutioResultsMutableArray;
}

//获取document目录并返回数据库目录
- (NSString *)DataFilePath
{
    NSString *ADataFilePathString;
    ADataFilePathString = [kLibrary stringByAppendingPathComponent:kFilename];
    return ADataFilePathString;
}
//创建、打开数据库
- (BOOL)OpenDataBase
{
    BOOL AIsOpenSuccessedBool;
    //获取数据库路径
    NSString *ADataFilePathString = [self DataFilePath];
    //文件管理器
    NSFileManager *AFileManager = [NSFileManager defaultManager];
    //判断数据库是否存在
    BOOL AIsDataBaseExistBool = [AFileManager fileExistsAtPath:ADataFilePathString];

    //如果数据库存在,则用sqlite3_open直接打开(不要担心,如果数据库不存在sqlite3_open会自动创建)
    if (AIsDataBaseExistBool) {
       // NSLog(@"Database file have already existed.");
        //打开数据库,这里的[path UTF8String]是将NSString转换为C字符串,因为SQLite3是采用可移植的C(而不是
        //Objective-C)编写的,它不知道什么是NSString.
        const char *ATempChar = [ADataFilePathString UTF8String];
        if(sqlite3_open(ATempChar, &FDatabaseSqlite) != SQLITE_OK) {

            //如果打开数据库失败则关闭数据库
            sqlite3_close(FDatabaseSqlite);
            //NSLog(@"Error: open database file failed.");
            [self SetErrorString:@"Error: open database file failed."];
            AIsOpenSuccessedBool = NO;
        }
        else {
            AIsOpenSuccessedBool = YES;
        }
    }
    //如果发现数据库不存在则利用sqlite3_open创建数据库(上面已经提到过),与上面相同,路径要转换为C字符串
    else if(sqlite3_open([ADataFilePathString UTF8String], &FDatabaseSqlite) == SQLITE_OK) {
        AIsOpenSuccessedBool = YES;
    }
    else {
        //如果创建并打开数据库失败则关闭数据库
        sqlite3_close(FDatabaseSqlite);
        //NSLog(@"Error: create and open database file failed.");
        [self SetErrorString:@"Error: create and open database file failed."];
        AIsOpenSuccessedBool = NO;
    }
    return AIsOpenSuccessedBool;
}
/*
- (BOOL)ExecuteSQL:(NSString *)ASQLString
{
    BOOL AIsSuccessedBool;
    if ([self OpenDataBase]) {
        sqlite3_stmt *AStatementSqlite3_stmt;
        NSString *AErrorString = nil;
        NSMutableArray *ASQLExecutioResultsMutableArray = [self GetSQLExecutioResultsMutableArray];
        [ASQLExecutioResultsMutableArray removeAllObjects];
        const char *ASQLChar = [ASQLString UTF8String];
        //sqlite3_prepare_v2 接口把一条SQL语句解析到statement结构里去. 使用该接口访问数据库是当前比较好的的一种方法
        NSInteger AParseSQLReturnInteger = sqlite3_prepare_v2(FDatabaseSqlite, ASQLChar, -1, &AStatementSqlite3_stmt, nil);
        //第一个参数跟前面一样,是个sqlite3 * 类型变量,
        //第二个参数是一个 sql 语句。
        //第三个参数我写的是-1,这个参数含义是前面 sql 语句的长度。如果小于0,sqlite会自动计算它的长度(把sql语句当成以\0结尾的字符串)。
        //第四个参数是sqlite3_stmt 的指针的指针。解析以后的sql语句就放在这个结构里。
        //第五个参数我也不知道是干什么的。为nil就可以了。
        //如果这个函数执行成功(返回值是 SQLITE_OK 且 statement 不为NULL ),那么下面就可以开始插入二进制数据。

        //如果SQL语句解析出错
        if(AParseSQLReturnInteger != SQLITE_OK) {
            //NSLog(@"Error: Parse SQL failed");
            AIsSuccessedBool = NO;
            AErrorString = [[NSString alloc] initWithFormat:@"Error: %s", sqlite3_errmsg(FDatabaseSqlite)];
            [self SetErrorString:AErrorString];
            [AErrorString release];
        }
        else {
            NSString *AOperationString = [ASQLString substringToIndex:6];
            if ([AOperationString caseInsensitiveCompare:@"create"] == NSOrderedSame) {
                [self CreateTable:ASQLChar Statement:AStatementSqlite3_stmt];
            }
            else if ([AOperationString caseInsensitiveCompare:@"INSERT"] == NSOrderedSame) {
                [self InsertData:ASQLChar Statement:AStatementSqlite3_stmt];
            }
            else if ([AOperationString caseInsensitiveCompare:@"delete"] == NSOrderedSame) {
                [self DeleteData:ASQLChar Statement:AStatementSqlite3_stmt];
            }
            else if ([AOperationString caseInsensitiveCompare:@"update"] == NSOrderedSame) {
                [self UpdateData:ASQLChar Statement:AStatementSqlite3_stmt];
            }
            else if ([AOperationString caseInsensitiveCompare:@"SELECT"] == NSOrderedSame) {
                [self SelectData:ASQLChar Statement:AStatementSqlite3_stmt];
            }
            else if ([[AOperationString substringToIndex:4] caseInsensitiveCompare:@"drop"] == NSOrderedSame) {
                [self DropTable:ASQLChar Statement:AStatementSqlite3_stmt];
            }
            AIsSuccessedBool = YES;
        }

        //释放sqlite3_stmt
        sqlite3_finalize(AStatementSqlite3_stmt);
        //关闭数据库
        sqlite3_close(FDatabaseSqlite);
    }
    return AIsSuccessedBool;
}
*/
- (BOOL)CreateTable:(NSString *)ASQLString
{
    BOOL AIsSuccessedBool=NO;
    if ([self OpenDataBase]) {

       // NSLog(@"CreateTable%@",ASQLString);

        sqlite3_stmt *AStatementSqlite3_stmt;
        NSString *AErrorString = nil;
        NSMutableArray *ASQLExecutioResultsMutableArray = [self GetSQLExecutioResultsMutableArray];
        [ASQLExecutioResultsMutableArray removeAllObjects];
        const char *ASQLChar = [ASQLString UTF8String];

        //sqlite3_prepare_v2 接口把一条SQL语句解析到statement结构里去. 使用该接口访问数据库是当前比较好的的一种方法
        NSInteger AParseSQLReturnInteger = sqlite3_prepare_v2(FDatabaseSqlite, ASQLChar, -1, &AStatementSqlite3_stmt, nil);

        //如果SQL语句解析出错
        if(AParseSQLReturnInteger != SQLITE_OK) {
            //NSLog(@"Error: Parse SQL failed");
            AIsSuccessedBool = NO;
            AErrorString = [[NSString alloc] initWithFormat:@"Error: %s", sqlite3_errmsg(FDatabaseSqlite)];
            [self SetErrorString:AErrorString];
            [AErrorString release];
        }
        else {
            //执行SQL语句
            int AExecuteSQLReturnInt = sqlite3_step(AStatementSqlite3_stmt);

            if (AExecuteSQLReturnInt != SQLITE_DONE)
            {
                AErrorString = [[NSString alloc] initWithFormat:@"Create Table failed!"];
                [self SetErrorString:AErrorString];
                [AErrorString release];
                AIsSuccessedBool = NO;
            }
            else {
                [self SetErrorString:@"Create Table Successed"];
                AIsSuccessedBool = YES;
            }
        }
        //释放sqlite3_stmt
        sqlite3_finalize(AStatementSqlite3_stmt);
        //关闭数据库
        sqlite3_close(FDatabaseSqlite);
    }
    return AIsSuccessedBool;
}

- (BOOL)InsertData:(NSString *)ASQLString
{
    BOOL AIsSuccessedBool=NO;
    if ([self OpenDataBase]) {
        sqlite3_stmt *AStatementSqlite3_stmt;
        NSString *AErrorString = nil;
        NSMutableArray *ASQLExecutioResultsMutableArray = [self GetSQLExecutioResultsMutableArray];
        [ASQLExecutioResultsMutableArray removeAllObjects];
        const char *ASQLChar = [ASQLString UTF8String];
        //sqlite3_prepare_v2 接口把一条SQL语句解析到statement结构里去. 使用该接口访问数据库是当前比较好的的一种方法
        NSInteger AParseSQLReturnInteger = sqlite3_prepare_v2(FDatabaseSqlite, ASQLChar, -1, &AStatementSqlite3_stmt, nil);

        //如果SQL语句解析出错
        if(AParseSQLReturnInteger != SQLITE_OK) {
            //NSLog(@"Error: Parse SQL failed");
            AIsSuccessedBool = NO;
            AErrorString = [[NSString alloc] initWithFormat:@"Error: %s", sqlite3_errmsg(FDatabaseSqlite)];
            [self SetErrorString:AErrorString];
            [AErrorString release];
        }
        else {
            //执行SQL语句
            int AExecuteSQLReturnInt = sqlite3_step(AStatementSqlite3_stmt);
            if (AExecuteSQLReturnInt == SQLITE_ERROR)
            {
                AErrorString = [[NSString alloc] initWithFormat:@"Insert Data failed!"];
                [self SetErrorString:AErrorString];
                [AErrorString release];
                AIsSuccessedBool = NO;
            }
            else {
                [self SetErrorString:@"Insert Data Successed"];
                AIsSuccessedBool = YES;
            }
        }
        //释放sqlite3_stmt
        sqlite3_finalize(AStatementSqlite3_stmt);
        //关闭数据库
        sqlite3_close(FDatabaseSqlite);
    }
    return AIsSuccessedBool;
}

- (BOOL)DeleteData:(NSString *)ASQLString
{
    BOOL AIsSuccessedBool=NO;
    if ([self OpenDataBase]) {
        sqlite3_stmt *AStatementSqlite3_stmt;
        NSString *AErrorString = nil;
        NSMutableArray *ASQLExecutioResultsMutableArray = [self GetSQLExecutioResultsMutableArray];
        [ASQLExecutioResultsMutableArray removeAllObjects];
        const char *ASQLChar = [ASQLString UTF8String];
        //sqlite3_prepare_v2 接口把一条SQL语句解析到statement结构里去. 使用该接口访问数据库是当前比较好的的一种方法
        NSInteger AParseSQLReturnInteger = sqlite3_prepare_v2(FDatabaseSqlite, ASQLChar, -1, &AStatementSqlite3_stmt, nil);

        //如果SQL语句解析出错
        if(AParseSQLReturnInteger != SQLITE_OK) {
            //NSLog(@"Error: Parse SQL failed");
            AIsSuccessedBool = NO;
            AErrorString = [[NSString alloc] initWithFormat:@"Error: %s", sqlite3_errmsg(FDatabaseSqlite)];
            [self SetErrorString:AErrorString];
            [AErrorString release];
        }
        else {
            //执行SQL语句
            int AExecuteSQLReturnInt = sqlite3_step(AStatementSqlite3_stmt);

            if (AExecuteSQLReturnInt == SQLITE_ERROR)
            {
                AErrorString = [[NSString alloc] initWithFormat:@"Delete Data failed!"];
                [self SetErrorString:AErrorString];
                [AErrorString release];
                AIsSuccessedBool = NO;
            }
            else {
                [self SetErrorString:@"Delete Data Successed"];
                AIsSuccessedBool = YES;
            }
        }
        //释放sqlite3_stmt
        sqlite3_finalize(AStatementSqlite3_stmt);
        //关闭数据库
        sqlite3_close(FDatabaseSqlite);
    }
    return AIsSuccessedBool;
}

- (BOOL)UpdateData:(NSString *)ASQLString
{
    BOOL AIsSuccessedBool=NO;
    if ([self OpenDataBase]) {
        sqlite3_stmt *AStatementSqlite3_stmt;
        NSString *AErrorString = nil;
        NSMutableArray *ASQLExecutioResultsMutableArray = [self GetSQLExecutioResultsMutableArray];
        [ASQLExecutioResultsMutableArray removeAllObjects];
        const char *ASQLChar = [ASQLString UTF8String];
        //sqlite3_prepare_v2 接口把一条SQL语句解析到statement结构里去. 使用该接口访问数据库是当前比较好的的一种方法
        NSInteger AParseSQLReturnInteger = sqlite3_prepare_v2(FDatabaseSqlite, ASQLChar, -1, &AStatementSqlite3_stmt, nil);

        //如果SQL语句解析出错
        if(AParseSQLReturnInteger != SQLITE_OK) {
            //NSLog(@"Error: Parse SQL failed");
            AIsSuccessedBool = NO;
            AErrorString = [[NSString alloc] initWithFormat:@"Error: %s", sqlite3_errmsg(FDatabaseSqlite)];
            [self SetErrorString:AErrorString];
            [AErrorString release];
        }
        else {
            //执行SQL语句
            int AExecuteSQLReturnInt = sqlite3_step(AStatementSqlite3_stmt);

            if (AExecuteSQLReturnInt == SQLITE_ERROR)
            {
                AErrorString = [[NSString alloc] initWithFormat:@"Update Data failed!"];
                [self SetErrorString:AErrorString];
                [AErrorString release];
                AIsSuccessedBool = NO;
            }
            else {
                [self SetErrorString:@"Update Data Successed"];
                AIsSuccessedBool = YES;
            }
        }
        //释放sqlite3_stmt
        sqlite3_finalize(AStatementSqlite3_stmt);
        //关闭数据库
        sqlite3_close(FDatabaseSqlite);
    }
    return AIsSuccessedBool;
}

- (BOOL)SelectData:(NSString *)ASQLString
{
    BOOL AIsSuccessedBool=NO;
    if ([self OpenDataBase]) {
        sqlite3_stmt *AStatementSqlite3_stmt;
        NSString *AErrorString = nil;
        NSMutableArray *ASQLExecutioResultsMutableArray = [self GetSQLExecutioResultsMutableArray];
        [ASQLExecutioResultsMutableArray removeAllObjects];
        const char *ASQLChar = [ASQLString UTF8String];
        //sqlite3_prepare_v2 接口把一条SQL语句解析到statement结构里去. 使用该接口访问数据库是当前比较好的的一种方法
        NSInteger AParseSQLReturnInteger = sqlite3_prepare_v2(FDatabaseSqlite, ASQLChar, -1, &AStatementSqlite3_stmt, nil);

        //如果SQL语句解析出错
        if(AParseSQLReturnInteger != SQLITE_OK) {
            //NSLog(@"Error: Parse SQL failed");
            AIsSuccessedBool = NO;
            AErrorString = [[NSString alloc] initWithFormat:@"Error: %s", sqlite3_errmsg(FDatabaseSqlite)];
            [self SetErrorString:AErrorString];
            [AErrorString release];
        }
        else {
            NSMutableArray *ASQLExecutioResultsMutableArray = [self GetSQLExecutioResultsMutableArray];
            char *ATempChar;
            NSUInteger ANumberOLineDatasUInteger;   //每行数据个数
            NSUInteger AIndexUInteger;
            NSString *ATempString;
            //NSUInteger ASqliteColumnTypeUInteger;   //某列数据类型
            //执行SQL语句
            while (sqlite3_step(AStatementSqlite3_stmt) == SQLITE_ROW) {
                ANumberOLineDatasUInteger = sqlite3_column_count(AStatementSqlite3_stmt);
                for (AIndexUInteger = 0; AIndexUInteger < ANumberOLineDatasUInteger; AIndexUInteger++) {
                     ATempChar = (char*)sqlite3_column_text(AStatementSqlite3_stmt, AIndexUInteger);
                     if (ATempChar!=nil) {
                         ATempString=[[NSString alloc] initWithCString:ATempChar encoding:NSUTF8StringEncoding];
                        }
                     else {
                        ATempString=[[NSString alloc] initWithFormat:@""];
                     }
                    [ASQLExecutioResultsMutableArray addObject:ATempString];
                     [ATempString release];
                }
            }
            AIsSuccessedBool = YES;

        }
        //释放sqlite3_stmt
        sqlite3_finalize(AStatementSqlite3_stmt);
        //关闭数据库
        sqlite3_close(FDatabaseSqlite);
    }
    return AIsSuccessedBool;
}
- (BOOL)SelectAllData:(NSString *)ASQLString
{
    BOOL AIsSuccessedBool=NO;
    if ([self OpenDataBase]) {
        sqlite3_stmt *AStatementSqlite3_stmt;
        NSString *AErrorString = nil;
        NSMutableArray *ASQLExecutioResultsMutableArray = [self GetSQLExecutioResultsMutableArray];
        [ASQLExecutioResultsMutableArray removeAllObjects];
        const char *ASQLChar = [ASQLString UTF8String];
        //sqlite3_prepare_v2 接口把一条SQL语句解析到statement结构里去. 使用该接口访问数据库是当前比较好的的一种方法
        NSInteger AParseSQLReturnInteger = sqlite3_prepare_v2(FDatabaseSqlite, ASQLChar, -1, &AStatementSqlite3_stmt, nil);

        //如果SQL语句解析出错
        if(AParseSQLReturnInteger != SQLITE_OK) {
            //NSLog(@"Error: Parse SQL failed");
            AIsSuccessedBool = NO;
            AErrorString = [[NSString alloc] initWithFormat:@"Error: %s", sqlite3_errmsg(FDatabaseSqlite)];
            [self SetErrorString:AErrorString];
            [AErrorString release];
        }
        else {
            NSMutableArray *ASQLExecutioResultsMutableArray = [self GetSQLExecutioResultsMutableArray];
            char *ATempChar;
            NSUInteger ANumberOLineDatasUInteger;   //每行数据个数
            NSUInteger AIndexUInteger;
            NSString *ATempString;
            //NSUInteger ASqliteColumnTypeUInteger;   //某列数据类型
            //执行SQL语句
            while (sqlite3_step(AStatementSqlite3_stmt) == SQLITE_ROW) {
                ANumberOLineDatasUInteger = sqlite3_column_count(AStatementSqlite3_stmt);
                NSMutableArray *ARowMutableArray=[[NSMutableArray alloc] initWithCapacity:1];
                for (AIndexUInteger = 0; AIndexUInteger < ANumberOLineDatasUInteger; AIndexUInteger++) {
                    ATempChar = (char*)sqlite3_column_text(AStatementSqlite3_stmt, AIndexUInteger);
                    if (ATempChar!=nil) {
                        ATempString=[[NSString alloc] initWithCString:ATempChar encoding:NSUTF8StringEncoding];
                    }
                    else {
                        ATempString=[[NSString alloc] initWithFormat:@""];
                    }
                    [ARowMutableArray addObject:ATempString];
                    [ATempString release];
                }
                [ASQLExecutioResultsMutableArray addObject:ARowMutableArray];
                [ARowMutableArray release];
            }
            AIsSuccessedBool = YES;

        }
        //释放sqlite3_stmt
        sqlite3_finalize(AStatementSqlite3_stmt);
        //关闭数据库
        sqlite3_close(FDatabaseSqlite);
    }
    return AIsSuccessedBool;
}

- (BOOL)DropTable:(NSString *)ASQLString
{
    BOOL AIsSuccessedBool=NO;
    if ([self OpenDataBase]) {
        sqlite3_stmt *AStatementSqlite3_stmt;
        NSString *AErrorString = nil;
        NSMutableArray *ASQLExecutioResultsMutableArray = [self GetSQLExecutioResultsMutableArray];
        [ASQLExecutioResultsMutableArray removeAllObjects];
        const char *ASQLChar = [ASQLString UTF8String];
        //sqlite3_prepare_v2 接口把一条SQL语句解析到statement结构里去. 使用该接口访问数据库是当前比较好的的一种方法
        NSInteger AParseSQLReturnInteger = sqlite3_prepare_v2(FDatabaseSqlite, ASQLChar, -1, &AStatementSqlite3_stmt, nil);

        //如果SQL语句解析出错
        if(AParseSQLReturnInteger != SQLITE_OK) {
            //NSLog(@"Error: Parse SQL failed");
            AIsSuccessedBool = NO;
            AErrorString = [[NSString alloc] initWithFormat:@"Error: %s", sqlite3_errmsg(FDatabaseSqlite)];
            [self SetErrorString:AErrorString];
            [AErrorString release];
        }
        else {
            //执行SQL语句
            int AExecuteSQLReturnInt = sqlite3_step(AStatementSqlite3_stmt);

            if (AExecuteSQLReturnInt == SQLITE_ERROR)
            {
                AErrorString = [[NSString alloc] initWithFormat:@"Drop Table failed!"];
                [self SetErrorString:AErrorString];
                [AErrorString release];
                AIsSuccessedBool = NO;
            }
            else {
                [self SetErrorString:@"Drop Table Successed"];
                AIsSuccessedBool = YES;
            }
        }
        //释放sqlite3_stmt
        sqlite3_finalize(AStatementSqlite3_stmt);
        //关闭数据库
        sqlite3_close(FDatabaseSqlite);
    }
    return AIsSuccessedBool;
}

@end

使用代码:

#import <Foundation/Foundation.h>
#import "SqlService/SQLService.h"
@interface OperatingTheCartTable : NSObject
{

}
/*Cart 表字段
 Id
 ProductId 产品ID
 ProductName  产品名臣
 Price  价格
 Quantity 数量
 ProductColor  产品颜色
 ProductSize 产品尺寸
 ProductSellAttributeId 产品销售属性ID
 */
+(NSInteger)GetNumberOfProduct;
+(BOOL)CreateCartTable;
+(NSMutableArray *)SelectFromCartTable;
+(NSMutableArray *)SelectFromCartTableWith:(NSInteger)AProductIdInteger;
+(BOOL)DeleteFromCartTable:(NSInteger)AIDInteger ProductSellAttributeId:(NSInteger)AProductSellAttributeIdInteger;
+(BOOL)InsertIntoCartTable:(NSInteger )AProductIdInteger ProductName:(NSString *)ANameString Price:(float )APriceFloat Quantity:(NSInteger)AQuantity ProductColor:(NSString *)AProductColor ProductSize:(NSString *)AProductSize ProductSellAttributeId:(NSInteger)AProductSellAttributeIdInteger;
+(BOOL)UpdateTheNumberOfCart:(NSInteger)AIDInteger Quantity:(NSInteger)AQuantityInteger ProductColor:(NSString *)AProductColor ProductSize:(NSString *)AProductSize ProductSellAttributeId:(NSInteger)AProductSellAttributeIdInteger;
#import "OperatingTheCartDatabase.h"

#define kLibrary [NSHomeDirectory() stringByAppendingPathComponent:@"Library"]
#define KDataBaseName @"Cart.sqlite"
@implementation OperatingTheCartTable

#pragma mark - 表 Cart
+(NSInteger)GetNumberOfProduct
{
    NSInteger ACountInteger=0;
    SQLService *ASQLService=[[[SQLService alloc] init] autorelease];
    NSString *ASelectString=[NSString stringWithFormat:@"select count(*) from Cart"];

    [ASQLService SelectData:ASelectString];
    NSMutableArray *AMutableArray=[ASQLService GetSQLExecutioResultsMutableArray];
    if(AMutableArray.count <= 0)
    {
        return  0;
    }
    ACountInteger = [[AMutableArray objectAtIndex:0] integerValue];
    return ACountInteger;
}

//ProductSellAttributeId
+(BOOL)CreateCartTable
{
    SQLService *ASQLService=[[SQLService alloc] init];
    NSString *ACreateBOOKSetingTable=[NSString stringWithFormat:@"create table if not exists Cart(Id INTEGER PRIMARY KEY autoincrement,ProductId INTEGER,ProductName nvarchar(250),Price float,Quantity INTEGER,ProductColor nvarchar(250),ProductSize nvarchar(250),ProductSellAttributeId INTEGER)"];
    if(![ASQLService CreateTable:ACreateBOOKSetingTable])
    {
        NSLog(@"创建表失败%@",[ASQLService GetErrorString]);
        [ASQLService release];
        return NO;
    }
    [ASQLService release];
    return YES;
}

+(NSMutableArray *)SelectFromCartTable
{
    SQLService *ASQLService=[[[SQLService alloc] init] autorelease];
    NSString *ASelectString=[NSString stringWithFormat:@"select * from Cart order by Id DESC"];

    [ASQLService SelectAllData:ASelectString];
    NSMutableArray *AMutableArray=[ASQLService GetSQLExecutioResultsMutableArray];
    for (int i=0; i<AMutableArray.count; i++) {
        NSMutableDictionary *AMutableDictionary=[[NSMutableDictionary alloc] initWithCapacity:1];
        NSMutableArray *ATempMutableArray=[AMutableArray objectAtIndex:i];

        [AMutableDictionary setValue:[ATempMutableArray objectAtIndex:1]forKey:@"ProductId"];
        [AMutableDictionary setValue:[ATempMutableArray objectAtIndex:2]forKey:@"ProductName"];
        [AMutableDictionary setValue:[ATempMutableArray objectAtIndex:3]forKey:@"Price"];
        [AMutableDictionary setValue:[ATempMutableArray objectAtIndex:4]forKey:@"Quantity"];
        if ([ATempMutableArray count] >= 6)
            [AMutableDictionary setValue:[ATempMutableArray objectAtIndex:5]forKey:@"ProductColor"];
        if ([ATempMutableArray count] >= 7)
           [AMutableDictionary setValue:[ATempMutableArray objectAtIndex:6]forKey:@"ProductSize"];
        if ([ATempMutableArray count] >= 8)
            [AMutableDictionary setValue:[ATempMutableArray objectAtIndex:7]forKey:@"ProductSellAttributeId"];

        [AMutableArray replaceObjectAtIndex:i withObject:AMutableDictionary];

        [AMutableDictionary release];
    }

    return AMutableArray;
}

//2013-10-31 11:41:57.457 CloudWork[2565:1a903] 红色,39,281
//2013-10-31 11:41:57.457 CloudWork[2565:1a903] 红色,37,278

+(NSMutableArray *)SelectFromCartTableWith:(NSInteger)AProductIdInteger
{
    SQLService *ASQLService=[[[SQLService alloc] init] autorelease];
    NSString *ASelectString=[NSString stringWithFormat:@"select * from Cart where ProductId=%d order by Id desc",AProductIdInteger];
    [ASQLService SelectAllData:ASelectString];
    NSMutableArray *AMutableArray=[ASQLService GetSQLExecutioResultsMutableArray];
    for (int i=0; i<AMutableArray.count; i++) {
        NSMutableDictionary *AMutableDictionary=[[NSMutableDictionary alloc] initWithCapacity:1];
        NSMutableArray *ATempMutableArray=[AMutableArray objectAtIndex:i];

        [AMutableDictionary setValue:[ATempMutableArray objectAtIndex:1]forKey:@"ProductId"];
        [AMutableDictionary setValue:[ATempMutableArray objectAtIndex:2]forKey:@"ProductName"];
        [AMutableDictionary setValue:[ATempMutableArray objectAtIndex:3]forKey:@"Price"];
        [AMutableDictionary setValue:[ATempMutableArray objectAtIndex:4]forKey:@"Quantity"];
        if ([ATempMutableArray count] >= 6)
            [AMutableDictionary setValue:[ATempMutableArray objectAtIndex:5]forKey:@"ProductColor"];
        if ([ATempMutableArray count] >= 7)
            [AMutableDictionary setValue:[ATempMutableArray objectAtIndex:6]forKey:@"ProductSize"];
        if ([ATempMutableArray count] >= 8)
            [AMutableDictionary setValue:[ATempMutableArray objectAtIndex:7]forKey:@"ProductSellAttributeId"];

        [AMutableArray replaceObjectAtIndex:i withObject:AMutableDictionary];
                  NSLog(@",%@,%@,%@,%@",[AMutableDictionary valueForKey:@"Quantity"],[AMutableDictionary valueForKey:@"ProductColor"],[AMutableDictionary valueForKey:@"ProductSize"],[AMutableDictionary valueForKey:@"ProductSellAttributeId"]);
        [AMutableDictionary release];
    }

    return AMutableArray;

}

+(BOOL)DeleteFromCartTable:(NSInteger)AIDInteger ProductSellAttributeId:(NSInteger)AProductSellAttributeIdInteger
{
    BOOL ABOOL=NO;
    NSString *ADeleteString=[NSString stringWithFormat:@"delete from Cart where ProductId=%d and ProductSellAttributeId=%d",AIDInteger,AProductSellAttributeIdInteger];
    SQLService *ASQLService=[[SQLService alloc] init];
    if([ASQLService DeleteData:ADeleteString])
    {
        ABOOL=YES;
    }
    else {
        ABOOL=NO;
    }
    [ASQLService release];
    return ABOOL;
}
+(BOOL)InsertIntoCartTable:(NSInteger )AProductIdInteger ProductName:(NSString *)ANameString Price:(float )APriceFloat Quantity:(NSInteger)AQuantity ProductColor:(NSString *)AProductColor ProductSize:(NSString *)AProductSize ProductSellAttributeId:(NSInteger)AProductSellAttributeIdInteger
{
    BOOL ABOOL=NO;
    NSString *AInsertString=[NSString stringWithFormat:@"insert into Cart(ProductId,ProductName,Price,Quantity,ProductColor,ProductSize,ProductSellAttributeId) values(%d,‘%@‘,%f,%d,‘%@‘,‘%@‘,%d)",AProductIdInteger,ANameString,APriceFloat,AQuantity,AProductColor,AProductSize,AProductSellAttributeIdInteger];
    SQLService *ASQLService=[[SQLService alloc] init];
    if([ASQLService InsertData:AInsertString])
    {
        ABOOL=YES;
    }
    else {
        ABOOL=NO;
    }
    [ASQLService release];
    return ABOOL;
}
+(BOOL)UpdateTheNumberOfCart:(NSInteger)AIDInteger Quantity:(NSInteger)AQuantityInteger ProductColor:(NSString *)AProductColor ProductSize:(NSString *)AProductSize ProductSellAttributeId:(NSInteger)AProductSellAttributeIdInteger
{
    BOOL ABOOL=NO;
    NSString *AUpdateString=[NSString stringWithFormat:@"update Cart set Quantity=%d,ProductColor=‘%@‘,ProductSize=‘%@‘ where ProductId=%d and ProductSellAttributeId=%d",AQuantityInteger,AProductColor,AProductSize,AIDInteger,AProductSellAttributeIdInteger];
    SQLService *ASQLService=[[SQLService alloc] init];

    if ([ASQLService UpdateData:AUpdateString]) {
        ABOOL=YES;
    }
    else {
        ABOOL=NO;
    }
    [ASQLService release];
    return ABOOL;
}
@end
时间: 2024-11-03 01:18:08

第六十六篇、OC_Sqlite数据库操作的相关文章

Egret入门学习日记 --- 第六十四篇(书中 19.4 节 内容)

第六十四篇(书中 19.4 节 内容) 昨天的问题,是 images 库自己本身的问题. 我单独使用都报错. 这是main.js文件代码: let images = require("images"); console.log(images); 这是cmd运行命令历史: Microsoft Windows [版本 10.0.16299.15] (c) 2017 Microsoft Corporation.保留所有权利. C:\Users\Administrator\Desktop\a&

第六十四篇、OC_计步器

计步器的实现方式主要有那么两种 1.通过直接调用系统的健康数据,基于HealthKit框架的,但是貌似是一小时更新一次数据.如果要实时获取步数,这种方式并不是最佳. 2.基于CoreMotion框架,顾名思义就是加速计/加速度传感器 >最早出现在iOS设备上的传感器之一 >加速计用于检测设备在X.Y.Z轴上的加速度 (哪个方向有力的作用) >加速计可以用于检测设备的摇晃,经典应用场景(例如摇一摇.计步器等) 源码: #import <Foundation/Foundation.h&

第六十八篇、OC_按照某一字段对数值进行排序

代码中是根据"create_time_" 进行排序   ascending:决定的是升序还是降序排序 NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"create_time_" ascending:Yes]; [dataArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

第六十九篇、OC_录制语音和播放语音功能的实现

录制: 1.设置全局属性 NSURL *recordedFile;//存放路径 AVAudioPlayer *player;//播放 AVAudioRecorder *recorder;//录制 NSString *recoderName;//文件名 2.设置存储路径 NSDateFormatter *formater = [[NSDateFormatter alloc] init]; [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"]; N

第六十五篇、iOS7自定义转场动画

自定义转场动画,在iOS7及以上的版本才开始出现的,在一些应用中,我们常常需要定制自定义的的跳转动画 1.遵守协议:<UIViewControllerAnimatedTransitioning> 2.协议的方法主要的是两个: // 指定动画的持续时长 1. (NSTimeInterval)transitionDuration: // 转场动画的具体内容 2. (void)animateTransition:(id <UIViewControllerContextTransitioning

小刘同学的第六十二篇博文

回家的第27天.开通博客园的62天.返校还有7天 今天算是看了点程序吧,因为今天开始看Node.js的视频了,就是没写代码... 不过还是不怎么静的下心来学,还是不够有毅力,自己可能还是不明确自己到底是怎么了. 看到第二次课了,看视频的时候不能截图就没截下来,不过遇到个问题,nvm不能装最新版,不知道哪来出了问题,老师说不能手动更新nvm update...但是我中午手贱试了下,然后现在就装不上latest版了,总是报错. 明早6点起要赶火车,就不多写了,今晚早点休息,大家晚安. 原文地址:ht

小刘同学的第六十六篇博文

夜深了,1:53了 今天其实破了一个大戒 距上一次写代码貌似就long long ago的事了 我想我需要一场彻底的改变 发自内心由内而外的改变 睡了 大家晚安 原文地址:https://www.cnblogs.com/xiaoliutongxue/p/8481719.html

小刘同学的第六十九篇博文

回学校的第一天 今天一路的颠簸,脑子有点混,而且可能还是没准备好新学期开始,适应在学校里的生活. 今天还没开始写代码,不过把VScode环境装上了,因为要用到命令行,想想sublime还是不太行. 各种插件装了一下,一直没写代码,不知道为什么,可能是太久没写了,自己有严重的为难情绪了. 很累. 大家早点休息,晚安. 原文地址:https://www.cnblogs.com/xiaoliutongxue/p/8495333.html

小刘同学的第一百六十四篇日记

想不到这一断就是一周时间了?????? 真的很不应该啊 希望这几天的奋斗能让我顺利通过今天的事业单位考试吧 时间也不早了,也不知道说些什么 反正自己对编程的兴趣好像又提不起来了 明天得早起总结一下 今晚就不多说了 大家晚安 好梦~ (很抱歉断更啊啊啊啊啊啊啊啊啊啊○○(><)○○) 原文地址:https://www.cnblogs.com/xiaoliutongxue/p/9165174.html