博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS数据库应用一:SQLite
阅读量:5139 次
发布时间:2019-06-13

本文共 10081 字,大约阅读时间需要 33 分钟。

 

 

 

保存数据的方式很多,plist files, XML, 或者 文本文件,但是效率不高。SQLite提供了在大数据中高效查询、检索的本地存储功能。

SQLite is an open source library, written in C, that implements a self-contained SQL relational database engine. You can use SQLite to store large amounts of relational data. The developers of SQLite have optimized it for use on embedded devices like the iPhone and iPad.

Although the Core Data application programming interface (API) is also designed to store data on iOS, its primary purpose is to persist objects created by your application. SQLite excels when pre- loading your application with a large amount of data, whereas Core Data excels at managing data created on the device.

 

一、建立数据库:

1、command-line

 

1、sqlite3 catalog.db//建立数据库2、//建表CREATE TABLE "main"."Product"("ID" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,"Name" TEXT, "ManufacturerID" INTEGER, "Details" TEXT, "Price" DOUBLE, "QuantityOnHand" INTEGER, "CountryOfOriginID" INTEGER, "Image" TEXT );CREATE TABLE "main"."Manufacturer"("ManufacturerID" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , "Name" TEXT NOT NULL );CREATE TABLE "main"."Country"("CountryID" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , "Country" TEXT NOT NULL );

2、使用火狐浏览器的SQLite Manager 插件

下载地址:

http://code.google.com/p/sqlite-manager

二,插入数据:

2、插入一行数据:

INSERT INTO "main"."Product" ("Name","ManufacturerID","Details","Price","QuantityOnHand", "CountryOfOriginID","Image")VALUES ('Widget A','1','Details of Widget A','1.29','5','1', 'Canvas_1');

3、从文件中导入数据到数据库:

.separator "\t".import "products.txt" Product

命令: .import

sqlite> .import 文件名 表名
注1: 不要忘了开头的点
注2: 这条语句不能用分号结束. 非SQL不需要分号结束.
注3: 需要查看默认的分隔符separator. 必须一致. 如果不一致可能导致sqlite字段分割错误.
        查看分隔符使用命令  .show , 如果不一致可直接修改, 比如:
        sqlite>.separator ","
        将分隔符转为逗号.

4、导出:

实现方式: 将输出重定向至文件.

命令: .output
sqlite> .output a.txt
然后输入sql语句, 查询出要导的数据. 查询后,数据不会显示在屏幕上,而直接写入文件.
结束后,输入
sqlite> .output stdout
将输出重定向至屏幕.
举例: 
将 tab_xx 中的数据导出到文件a.txt
sqlite> .output a.txt
sqlite> select * from tab_xx;

在屏幕显示:

sqlite> .output stdout

sqlite> select * from tab_xx;

 三、在iOS软件中使用SQLite:

1、首先要对数据建模

2、抽象出操作数据库的API,以便以后更换数据库。

#import 
// This includes the header for the SQLite library.#import
#import "Product.h"@interface DBAccess : NSObject { }- (NSMutableArray*) getAllProducts;- (void) closeDatabase;- (void)initializeDatabase;@end
#import "DBAccess.h"@implementation DBAccess// Reference to the SQLite database.sqlite3* database;-(id) init{    //  Call super init to invoke superclass initiation code    if ((self = [super init]))    {        //  set the reference to the database        [self initializeDatabase];    }    return self;}// Open the database connection- (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));    }}- (NSMutableArray*) getAllProducts{    //  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.        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是数据模型的对象            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] : @"";                        // Add the product to the products array            [products addObject:product];         }        // finalize the statement to release its resources        sqlite3_finalize(statement);    }    else {        NSLog(@"Problem with the database:");        NSLog(@"%d",sqlResult);    }        return products;    }@end

 

3、

#import 
sqlite3 *contactDB; NSString *docsDir; NSArray *dirPaths; // Get the documents directory dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); docsDir = [dirPaths objectAtIndex:0]; // Build the path to the database file NSString *databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"contacts.db"]]; NSFileManager *filemgr = [NSFileManager defaultManager]; if ([filemgr fileExistsAtPath:databasePath] == NO) { const char *dbpath = [databasePath UTF8String]; if (sqlite3_open(dbpath, &contactDB)==SQLITE_OK) { char *errMsg; const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT,PHONE TEXT)"; if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg)!=SQLITE_OK) { status.text = @"创建表失败\n"; } } else { status.text = @"创建/打开数据库失败"; } }

 

4、向数据库插入数据:

- (IBAction)SaveToDataBase:(id)sender {    sqlite3_stmt *statement;        const char *dbpath = [databasePath UTF8String];        if (sqlite3_open(dbpath, &contactDB)==SQLITE_OK) {        NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO CONTACTS (name,address,phone) VALUES(\"%@\",\"%@\",\"%@\")",name.text,address.text,phone.text];        const char *insert_stmt = [insertSQL UTF8String];        sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);        if (sqlite3_step(statement)==SQLITE_DONE) {            status.text = @"已存储到数据库";            name.text = @"";            address.text = @"";            phone.text = @"";        }        else        {            status.text = @"保存失败";        }        sqlite3_finalize(statement);        sqlite3_close(contactDB);    }}

5、查询数据库库:

- (IBAction)SearchFromDataBase:(id)sender {    const char *dbpath = [databasePath UTF8String];    sqlite3_stmt *statement;        if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)     {        NSString *querySQL = [NSString stringWithFormat:@"SELECT address,phone from contacts where name=\"%@\"",name.text];        const char *query_stmt = [querySQL UTF8String];        if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)         {            if (sqlite3_step(statement) == SQLITE_ROW)             {                NSString *addressField = [[NSString alloc] initWithUTF8String:(const char *)sqlite3_column_text(statement, 0)];                address.text = addressField;                                NSString *phoneField = [[NSString alloc] initWithUTF8String:(const char *)sqlite3_column_text(statement, 1    )];                phone.text = phoneField;                                status.text = @"已查到结果";                [addressField release];                [phoneField release];            }            else {                status.text = @"未查到结果";                address.text = @"";                phone.text = @"";            }            sqlite3_finalize(statement);        }                sqlite3_close(contactDB);    }}

 

使用:

//  Get the DBAccess object;    DBAccess *dbAccess = [[DBAccess alloc] init];        //  Get the products array from the database    self.products = [dbAccess getAllProducts];        //  Close the database because we are finished with it    [dbAccess closeDatabase];

 

tips:

1、读取文件:

NSString *textFileContents = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"myTextFile" ofType:@"txt"] encoding:NSUTF8StringEncoding error:&error];// If there are no results, something went wrong if (fileContents == nil) {// an error occurred  NSLog(@"Error reading text file. %@", [error localizedFailureReason]);}NSArray *lines = [textFileContents componentsSeparatedByString:@"\n"]; NSLog(@"Number of lines in the file:%d", [lines count] );

 

转载于:https://www.cnblogs.com/shangdahao/archive/2013/05/29/3104053.html

你可能感兴趣的文章
WinCE应用程序开发---进程间通信
查看>>
自动化测试开发环境搭建
查看>>
CrashHandler实例
查看>>
XMPP框架的分析、导入及问题解决
查看>>
bootstrap用法小计
查看>>
8.QList QMap QVariant
查看>>
Python学习第二十一节(继承顺序,super)
查看>>
Word2016怎么和mathtype兼容
查看>>
[文章备份]本站有自建KMS用于激活Windows/Office
查看>>
【HeadFirst 设计模式学习笔记】21 备忘录(Memento)模式拾零
查看>>
Java实现单向链表反转
查看>>
【原创】MapReduce程序如何在集群上执行
查看>>
Bean进行操作的相关工具方法
查看>>
Struts2学习笔记 - Part.01
查看>>
转载->C#中的委托的使用和讲解
查看>>
WMS
查看>>
基于mykernel完成多进程的简单内核
查看>>
Python入门 值内存管理与所有的关键字
查看>>
Python 之类型转换
查看>>
nginx的access_log与error_log(三)
查看>>