sqlite的应用实例

sqlite 的介绍:
sqlite是c语言写的一个开源库,它实现的是一个开源的自自包含的SQL关系型的数据库引擎,可以使用sqlite存储大量关联数据。可以嵌入到iPhone或者ipad的设备上面。

优点:
1、sqlite是一个完全自包含(独立性比较高)的Sql数据库引擎,
  1)所以所有的数据库数据都被存储在一个单独的、跨平台的磁盘中;
  2)它需要几个外部库和一点点的操作系统的支持。
2、sqlite所占用的空间是非常的晓得。大概只是300k
3、sqlite不需要配置、安装以及管理员的过程。
4、sqlite支持了很多的sql的特性,然而还有一些特性没有支持,可以查看官方文档;

区别:
core Data:core Data应用程序编程接口(API)被设计用来在ios上存储数据。擅长管理在设备上创建数据。
(1)是一个框架,而不是一个关系型数据库,主要的目的是提供给开发人员一个框架,用来保存应用程序创建的对象;
(2)可以使用丰富的API集在代码中操作这些对象,也就是mvc中的模型的创建;
(3)可以使用sqlite以及其他的存储类型作为数据的后台存储(但:注意它不是关系型数据库的实现)。
(4)它不是以开发人员直接访问存储。如果只需持久化应用程序使用期间使用期间创建的对象,则应该考虑使用core Data。

sqlite:当需要预先加载具有大量数据的应用程序的时候,sqlite表现就比较突出。eg:地图上的GPS功能,这些表现为预加载比较强烈的功能。如果需要使用关系型数据库存储的功能,应该考虑直接使用sqlite,

有关sqlite3中的一些详细内容的引用:
1、sqlite3 catalog.db 启动sqlite3工具,并且创建了一个catalog.db的数据库
2、attach database 命令 、附加现有的数据库到sqlite工具 、或者指定的文件不存在的时候创建数据库
3、可以附加多个数据库大一个命令行工具实例,并且以数据库名称.表名称的格式使用点符号在每一个数据库中引用数据
4、可以将一个数据从一个数据库迁移到另外一个数据库中。

sqlite中存在很多元命令(metacommmands),用来控制工具自身。
eg:sqlite中以“.”符号执行的元命令是不需要“;”符号结束的。可以在进入sqlite的环境下之后执行 .help 来查看命令。
而一些其他语句没有以“.”符号开始的时候,就需要“;”符号结束。

xcode中使用sqlite3数据库:
0、添加所需要的框架libsqlite3.0.dylib ,这个动态库集成了想所有的sqlite的操作,显示接口。
1、添加数据库,eg:添加catalog.db 到xcode项目的suport的目录下。
2、创建模型,eg:对应着数据库中的表,然后就是创建和数据库职工的字段一样的名字的属性,这样不容易出现错误。转化不用那么麻烦。(属性  <——————> 字段)它们之间一一对应。
3、创建连接数据库的底层类,并且创建获取数据,修改数据的等等方法,这里需要调用数据库sqlite的接口的方法。

声明:下面的代码是引用别人的:

代码截图:

  运行的结果图:

下面是程序中主要的代码:

模型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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值