时间:2021-07-01 10:21:17 帮助过:23人阅读
声明:下面的代码是引用别人的:
代码截图:
  运行的结果图:
下面是程序中主要的代码:
模型product的代码:
product.h 的文件爱你
#import <Foundation/Foundation.h>
//这个就是模型类,对应这数据库中的属性字段。
@interface Product : NSObject {
    int ID;
    NSString* name;
    NSString* manufacturer;
    NSString* details;
    float price;
    int quantity;
    NSString* countryOfOrigin;
    NSString* image;
}
@property (nonatomic) int ID;
@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *manufacturer;
@property (strong, nonatomic) NSString *details;
@property (nonatomic) float price;
@property (nonatomic) int quantity;
@property (strong, nonatomic) NSString *countryOfOrigin;
@property (strong, nonatomic) NSString *image;
@end
product.m文件,尤其这样实现是为了和在字段中的属性名字对应。 #import "Product.h" @implementation Product @synthesize ID; @synthesize name; @synthesize manufacturer; @synthesize details; @synthesize price; @synthesize quantity; @synthesize countryOfOrigin; @synthesize image; @end
下面是DBAccess类的代码:
DBAccess.h文件。
#import <Foundation/Foundation.h>
// This includes the header for the SQLite library.
#import <sqlite3.h>
#import "Product.h"
//用来获取数据库中的数据,添加到模型中库
@interface DBAccess : NSObject {
    
    
}
//获取的数组方法
- (NSMutableArray*) getAllProducts;
//关闭数据库
- (void) closeDatabase;
//初始化数据库,包括打开数据库
- (void)initializeDatabase;
@end
DBAccess.m文件。
#import "DBAccess.h"
@implementation DBAccess
// Reference to the SQLite database.
sqlite3* database;
//初始化方法,集成NSObject类,启动的时候就会调用这个方法。
-(id) init
{
    if ((self = [super init]))
    {
        [self initializeDatabase];
    }
    return self;
}
// 获取数据库文件、打开、连接
- (void)initializeDatabase {
    
    // Get the database from the application bundle.
    NSString *path = [[NSBundle mainBundle]
                      pathForResource:@"catalog"
                      ofType:@"db"];
    
    // Open the database.
    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
    {
        NSLog(@"Opening Database");
    }
    else
    {
        // Call close to properly clean up
        sqlite3_close(database);
        NSAssert1(0, @"Failed to open database: ‘%s’.",
                  sqlite3_errmsg(database));
    }
}
//关闭数据库
-(void) closeDatabase
{
    // Close the database.
    if (sqlite3_close(database) != SQLITE_OK) {
        NSAssert1(0, @"Error: failed to close database: ‘%s’.",
                  sqlite3_errmsg(database));
    }
}
//获取数据库中product的所有记录存储到数组中
- (NSMutableArray*) getAllProducts
{
    NSLog(@"获取数据");
    //  The array of products that we will create
    NSMutableArray *products = [[NSMutableArray alloc] init];
    //  The SQL statement that we plan on executing against the database
    const char *sql = "SELECT product.ID,product.Name,     Manufacturer.name,product.details,product.price,    product.quantityonhand, country.country,     product.image FROM Product,Manufacturer,     Country where manufacturer.manufacturerid=product.manufacturerid     and product.countryoforiginid=country.countryid";
    //  The SQLite statement object that will hold our result set
    sqlite3_stmt *statement;
    
    // Prepare the statement to compile the SQL query into byte-code
    int sqlResult = sqlite3_prepare_v2(database, sql, -1, &statement, NULL);
    if ( sqlResult== SQLITE_OK) {
        // Step through the results - once for each row.
        //#define SQLITE_ROW   sqlite3_step() has another row ready
        while (sqlite3_step(statement) == SQLITE_ROW) {
            //  allocate a Product object to add to products array
            Product  *product = [[Product alloc] init];
            // The second parameter is the column index (0 based) in
            // the result set.
            char *name = (char *)sqlite3_column_text(statement, 1);
            char *manufacturer = (char *)sqlite3_column_text(statement, 2);
            char *details = (char *)sqlite3_column_text(statement, 3);
            char *countryOfOrigin = (char *)sqlite3_column_text(statement, 6);
            char *image = (char *)sqlite3_column_text(statement, 7);
            
            //  Set all the attributes of the product
            product.ID = sqlite3_column_int(statement, 0);
            product.name = (name) ? [NSString stringWithUTF8String:name] : @"";
            product.manufacturer = (manufacturer) ? [NSString
                                                     stringWithUTF8String:manufacturer] : @"";
            product.details = (details) ? [NSString stringWithUTF8String:details] : @"";
            product.price = sqlite3_column_double(statement, 4);
            product.quantity = sqlite3_column_int(statement, 5);
            product.countryOfOrigin = (countryOfOrigin) ? [NSString
                                                           stringWithUTF8String:countryOfOrigin] : @"";
            product.image = (image) ? [NSString stringWithUTF8String:image] : @"";
            
            // 将产品添加到Products数组中并且移到下一行
            [products addObject:product];
        }
        //释放和编译器语句有关的资源
        sqlite3_finalize(statement);
    }
    else {
        NSLog(@"Problem with the database:");
        NSLog(@"%d",sqlResult);
    }
    return products;
}
@end
 在Controller中使用来显示在View中的代码:
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    DBAccess *dbAccess = [[DBAccess alloc] init];
    
    self.products = [dbAccess getAllProducts]; //前面应该定义了products这个属性。
    
    [dbAccess closeDatabase];
    
}
源代码下载连接:
http://www.wrox.com/WileyCDA/WroxTitle/Professional-iOS-Database-Application-Programming-2nd-Edition.productCd-1118391845,descCd-DOWNLOAD.html
版权声明:本文为博主原创文章,未经博主允许不得转载。
sqlite的应用实例
标签:sqlite3 模型 数据库连接 数据库中获取数据 数据库