iOS关于sqlite3操作

iPhone中支持通过sqlite3来訪问iPhone本地的数据库。

详细用法例如以下

1:加入开发包libsqlite3.0.dylib

首先是设置项目文件。在项目中加入iPhone版的sqlite3的数据库的开发包。在项目下的Frameworks点击右键。然后选择libsqlite3.0.dylib文件。

libsqlite3.0.dylib文件地址: 

/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.2.sdk/usr/lib/libsqlite3.0.dylib

2,代码中的操作:

那么接下来是代码了。

1 首先获取iPhone上sqlite3的数据库文件的地址

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *path = [documentsDirectory stringByAppendingPathComponent:@"database_name"];

打开iPhone上的sqlite3的数据库文件

sqlite3 *database;

sqlite3_open([path UTF8String], &database);

3 准备sql文---sql语句

sqlite3_stmt *stmt;

const char *sql = "SELECT * FROM table_name WHERE pk=? and name=?";

sqlite3_prepare_v2(database, sql, -1, &stmt, NULL);

邦定參数

// 邦定第一个int參数

sqlite3_bind_int(stmt, 1, 1);

// 邦定第二个字符串參数

sqlite3_bind_text(stmt, 2, [title UTF8String], -1, SQLITE_TRANSIENT);

运行sql文

sqlite3_step(stmt);

释放sql文资源

sqlite3_finalize(stmt);

关闭iPhone上的sqlite3的数据库

sqlite3_close(database);





http://hi.baidu.com/clickto/blog/item/0c6904f787c34125720eec87.html



下面演示一下使用sqlite的步骤,先创建一个数据库,然后查询当中的内容。2个重要结构体和5个主要函数:



sqlite3               *pdb, 数据库句柄,跟文件句柄FILE非常类似



sqlite3_stmt      *stmt, 这个相当于ODBC的Command对象,用于保存编译好的SQL语句







sqlite3_open(),   打开数据库



sqlite3_exec(),   运行非查询的sql语句



sqlite3_prepare(), 准备sql语句,运行select语句或者要使用parameter bind时,用这个函数(封装了sqlite3_exec).



Sqlite3_step(), 在调用sqlite3_prepare后,使用这个函数在记录集中移动。



Sqlite3_close(), 关闭数据库文件







另一系列的函数。用于从记录集字段中获取数据,如



sqlite3_column_text(), 取text类型的数据。



sqlite3_column_blob(),取blob类型的数据



sqlite3_column_int(), 取int类型的数据



PreparedStatement方式处理SQL请求的过程

特点:能够绑定參数,生成过程。运行的时候像是ADO一样。每次返回一行结果。



1. 首先建立statement对象:

int sqlite3_prepare(

sqlite3 *db,            /* Database handle */

const char *zSql,       /* SQL statement, UTF-8 encoded */

int nBytes,             /* Length of zSql in bytes. */

sqlite3_stmt **ppStmt,  /* OUT: Statement handle */

const char **pzTail     /* OUT: Pointer to unused portion of zSql */

);



2. 绑定过程中的參数(假设有没有确定的參数)

int sqlite3_bind_xxxx(sqlite3_stmt*, int, ...);

第二个int类型參数-表示參数的在SQL中的序号(从1開始)。

第三个參数为要绑定參数的值。

对于blob和text数值的额外參数:

第四參数是字符串(Unicode 8or16)的长度,不包含结束'\0'。

第五个參数。类型为void(*)(void*),表示SQLite处理结束后用于清理參数字符串的函数。

没有进行绑定的未知參数将被觉得是NULL。



3. 运行过程

int sqlite3_step(sqlite3_stmt*);

可能的返回值:

*SQLITE_BUSY:   数据库被锁定,须要等待再次尝试直到成功。

*SQLITE_DONE:   成功运行过程(须要再次运行一遍以恢复数据库状态)

*SQLITE_ROW:    返回一行结果(使用sqlite3_column_xxx(sqlite3_stmt*,, int iCol)得到每一列的结果。

再次调用将返回下一行的结果。

*SQLITE_ERROR:  执行错误,过程无法再次调用(错误内容參考sqlite3_errmsg函数返回值)

*SQLITE_MISUSE: 错误的使用了本函数(通常是过程没有正确的初始化)



4. 结束的时候清理statement对象

int sqlite3_finalize(sqlite3_stmt *pStmt);

应该在关闭数据库之前清理过程中占用的资源。



5. 重置过程的运行 

int sqlite3_reset(sqlite3_stmt *pStmt);

过程将回到没有运行之前的状态,绑定的參数不会变化。



样例:

创建数据库



 NSString *docsDir;

  NSArray *dirPaths;

    

    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    docsDir = [dirPaths objectAtIndex:0];

    databasePath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:@"info.db"]];

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if ([fileManager fileExistsAtPath:databasePath]==NO) {

        const char *dbpath = [databasePath UTF8String];

        if (sqlite3_open(dbpath, &dataBase)==SQLITE_OK) {

            char *errmsg;

            const char *createSql = "CREATE TABLE IF NOT EXISTS INFO (ID INTEGER PRIMARY KEY AUTOINCREMENT,NUM TEXT,CLASSNAME TEXT,NAME TEXT)";

            if (sqlite3_exec(dataBase, createSql, NULL, NULL, &errmsg)!=SQLITE_OK) {

                status.text = @"create table failed";

                

            }

        }

        else{

            status.text = @"create/open failled";

        }

    }



保存

 sqlite3_stmt *statement;

    

    const char *dbpath = [databasePath UTF8String];

    

    if (sqlite3_open(dbpath, &dataBase)==SQLITE_OK) {

        if ([num.text isEqualToString:@""]) {

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"SORRY!" message:@"number cannot be nil!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

            [alert show];

        }

        else {

        

        NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO INFO (num,classname,name) VALUES(\"%@\",\"%@\",\"%@\")",num.text,classname.text,name.text];

        const char *insertsatement = [insertSql UTF8String];

        sqlite3_prepare_v2(dataBase, insertsatement, -1, &statement, NULL);

        if (sqlite3_step(statement)==SQLITE_DONE) {

            status.text = @"save to DB.";

            num.text = @"";

            classname.text = @"";

            name.text = @"";

        }

        else {

            status.text = @"save failed!";

        }

        sqlite3_finalize(statement);

        sqlite3_close(dataBase);

        }

    }



清除:



   num.text = @"";

    classname.text = @"";

    name.text = @"";

    status.text = @"";





查询:

 const char *dbpath = [databasePath UTF8String];

    

    sqlite3_stmt *statement;

    

    if (sqlite3_open(dbpath, &dataBase)==SQLITE_OK) {

        NSString *querySQL = [NSString stringWithFormat:@"SELECT classname,name from info where num=\"%@\"",num.text];

        const char *querystatement = [querySQL UTF8String];

        if (sqlite3_prepare_v2(dataBase, querystatement, -1, &statement, NULL)==SQLITE_OK) {

            if (sqlite3_step(statement)==SQLITE_ROW) {

                NSString *classnameField = [[NSString alloc] initWithUTF8String:(const char *)sqlite3_column_text(statement, 0)];

                classname.text = classnameField;

                NSString *nameField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];

                name.text = nameField;

                

                status.text = @"find~~~";                

            }

            else {

                status.text = @"did not find you need.";

            }

            sqlite3_finalize(statement);

        }

        sqlite3_close(dataBase);

    }









其它工具函数

1. 得到结果总共的行数

int sqlite3_column_count(sqlite3_stmt *pStmt);

假设过程没有返回值,如update,将返回0



2. 得到当前行中包括的数据个数

int sqlite3_data_count(sqlite3_stmt *pStmt);

假设sqlite3_step返回SQLITE_ROW,能够得到列数。否则为零。

3. 得到数据行中某个列的数据

sqlite3_column_xxx(sqlite3_stmt*, int iCol);

在sqlite3_step返回SQLITE_ROW后,使用它得到第iCol列的数据。

当中的xxx代表:

blob:指向保存数据内存的指针

bytes, bytes16: 得到该blob类型数据的大小,或者text转换为UTF8/UTF16的字符串长度。

double, int, int64: 数值

text,text16:字符串指针

type:该列的数据类型(SQLITE_INTEGER,SQLITE_FLOAT。SQLITE_TEXT,SQLITE_BLOB,SQLITE_NULL)

注意:假设对该列使用了不同与该列本身类型适合的数据读取方法,得到的数值将是转换过的结果。



4. 得到数据行中某个列的数据的类型

int sqlite3_column_type(sqlite3_stmt*, int iCol);

返回值:SQLITE_INTEGER。SQLITE_FLOAT。SQLITE_TEXT,SQLITE_BLOB,SQLITE_NULL

使用的方法和sqlite3_column_xxx()函数类似。



//////////////////////////////////////Sqlite 資料庫檔案的產生

MAC 上有許多應用程式都能够用來產生它,有 UI 界面非常方便。

但假设不想另外安裝軟體。MAC 系統也內建 sqlite3 的元件,可由 console 來建立。首先我們先開啟不论什么一款文書編輯軟體。以 sql 語法來手動建立,並存成 data.sql。

1BEGINTRANSACTION;
2CREATETABLE'Info'(_id INTEGERPRIMARYKEY, 'Name'TEXT, 'Tel'TEXT, 'Address'TEXT);
3INSERTINTO'Info'VALUES(1,'Richie','1234567','台中市');
4INSERTINTO'Info'VALUES(2,'Eric','7654321','台北市');
5INSERTINTO'Info'VALUES(3,'Andy','1234321','高雄市');
6COMMIT;

然後在 console 下達下面指令 來產生 data.rdb 這個 sqlite file

1sqlite3 data.rdb < data.sql

iOS 專案使用 Sqlite 資料庫

先將剛才產生的資料庫增加專案中,然後在專案中增加 libsqlite3.0.dylib。

接下來开始撰寫程式碼了,xxxAppDelegate.h 必須 import sqlite3.h,並宣告一個 sqlite3 結構。

1#import "sqlite3.h"
2  
3@interfacexxxAppDelegate : NSObject<UIApplicationDelegate>
4{
5    sqlite3* database;
6}

在 xxxAppDelegate.m 的 didFinishLaunchingWithOptions 函式 开始增加相關程式碼

1- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
2{
3    // 檢查資料庫是否存在,不存在時則 copy
4    NSString*path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
5    NSString*file = [path stringByAppendingPathComponent:@"data.rdb"];
6    if([[NSFileManagerdefaultManager] fileExistsAtPath:file] == FALSE)
7    {
8        NSString*fromFile = [[NSBundlemainBundle] pathForResource:@"data.rdb"ofType:nil];
9        [[NSFileManagerdefaultManager] copyItemAtPath:fromFile toPath:file error:nil];
10    }
11    // open
12    if(sqlite3_open([file UTF8String], &database) != SQLITE_OK)
13        NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
14  
15    self.window.rootViewController = self.viewController;
16    [self.window makeKeyAndVisible];
17    returnYES;
18}
19  
20- (void)dealloc
21{
22    sqlite3_close(database);
23    [superdealloc];
24}

簡 單說明一下,將 data.rdb 增加專案中後,該資料庫會出現在 app 套件內。但每個 app 就仅仅有專屬 Documents 目錄能够讀寫。所以必須判斷 Documents 目錄下該檔案是否存在。假设不存在則 copy 過去該目錄後再 open 資料庫。至於為什麼做判斷?為什麼不每次都 copy 過去就可以?因為假设不希望該資料庫在每次 app 版本号更新後,都會被覆蓋掉,就得做檔案存在與否的判斷。



讀取資料庫

有成功 open 資料庫之後。就能够开始進行讀寫了。

讀取資料庫的方法,其實也是非常簡單,仅仅要熟悉 SQL 語法,應該就沒什麼問題了。

1NSString*sql = [NSStringstringWithFormat:@"SELECT * FROM Event "];
2sqlite3_stmt *statement;
3if(sqlite3_prepare_v2(database, 1, -1, &statement, NULL) == SQLITE_OK)
4{
5    while (sqlite3_step(statement) == SQLITE_ROW)
6    {
7        NSString*strValue = [NSStringstringWithUTF8String:(char*)sqlite3_column_text(statement, 0)];
8        intintValue = sqlite3_column_int(statement, 1);
9    }
10}
11sqlite3_finalize(statement);

当中必須注意的是 sqlite3_column_text, sqlite3_column_int 負責取得資料,必須指定是哪個 column index。



執行 SQL 命令

上述是 SELECT 的使用方法,可是假设须要做 INSERT, DELETE, UPDATE 等動作時。則更是簡單,仅仅需下面指令就可以。

1char*errMsg;
2NSString*sql = [NSStringstringWithFormat:@"CREATE TABLE 'Info' (_id INTEGER PRIMARY KEY, 'Name' TEXT, 'Tel' TEXT, 'Address' TEXT)"];
3sqlite3_exec(database, 1, nil, nil, &errMsg);

ios在SQLite3基本操作的更多相关文章

  1. ios对SQLite3的使用

    ios对SQLite3的使用 一.在Firefox中打开sqlite3(如果没有,选择工具->附加组件,添加即可)新建sqlite3数据库,Contacts, 建立一个members表,字段 i ...

  2. C语言SQLite3基本操作Demo

    /************************************************************************** * C语言SQLite3基本操作Demo * 声 ...

  3. 使用iOS原生sqlite3框架对sqlite数据库进行操作

    摘要: iOS中sqlite3框架可以很好的对sqlite数据库进行支持,通过面向对象的封装,可以更易于开发者使用. 使用iOS原生sqlite3框架对sqlite数据库进行操作 一.引言 sqlit ...

  4. iOS关于sqlite3操作

    原文:http://hi.baidu.com/clickto/blog/item/0c6904f787c34125720eec87.html iPhone中支持通过sqlite3来访问iPhone本地 ...

  5. iOS之Sqlite3封装

    一.代码下载 代码下载地址 二.实例效果展示 imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="效果图二.png&q ...

  6. iOS:转载sqlite3

     SQLITE3 使用总结 2012-08-21 13:48:28 分类: SQLite/嵌入式数据库 SQLITE3 使用总结 2009-09-16 07:36 2624人阅读 评论(10) 收藏  ...

  7. iOS 数据库sqlite3.0操作--超简单--看我就够啦

    iOS客户端数据存储的方式有很多,下面主要是介绍苹果自带的sqlite3.0的使用方法. 首先导入sqlite3.0的框架.然后导入头文件#import <sqlite3.h>就行了 下面 ...

  8. iOS- 简单说说iOS移动客户端SQLite3的基本使用

    1.为什么要使用SQLite3? •大量数据需要存储 •管理数据,存储数据   SQLite是一种关系型数据库(也是目前移动客户端的主流数据库)     2.SQLite3的几种存储类型   a.NU ...

  9. sqlite3基本操作

    在移动设备上进行高性能高效率的大量数据存储,我们一般用得时sqlite这款轻巧型的数据库,这里介绍其增删改查基本功能 在ios开发中我们需要先导入"libsqlite3.dylib" ...

随机推荐

  1. LAN路由

    一.实验的目的:   实现不同子网之前的信息交流      二.如果 1.虚拟子网 VMnet8:192.168.233.0/24 VMnet1:172.16.1.0/24 2.虚拟机vm1 ip:1 ...

  2. 用jsp写注冊页面

    包含单选框.多选框.session的应用,页面自己主动跳转,中文乱码的处理,入门级 对于中文乱码的处理,注意几点:注冊页面数据提交方式为post不能忘了写,页面编码方式为gbk,处理提交信息的doRe ...

  3. Company Story | Vistaprint

    Company Story | Vistaprint Company Story A Gap in the Small Business Marketplace It’s rare that a hi ...

  4. poj 3278 Catch That Cow (bfs搜索)

    Catch That Cow Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 46715   Accepted: 14673 ...

  5. poj3207(two-sat)

    传送门:Ikki's Story IV - Panda's Trick 题意:给定一个圆,圆上一些点.两点一线.现给出一些线,这些线可以在圆内连起来,也可以在圆外.问有没有可能所有的线画完且不出现相交 ...

  6. Hlg 1832 【线段树 && RMQ】.cpp

    题意: 在给出的区间内求出最大买进卖出的差价. 思路: 对于弱数据:维护一个从左到右的最大差价和最小值.即当发现当前值比最小值小的时候更新最小值,否则看一下当前值与之前最小值的差价是否比最大差价大,是 ...

  7. 【转】Vim学习资料

    初学资料:1:一个介绍VIM操作的游戏,十分适合初学者.只是:不要怕英文.vim-adventures.com2:http://blog.csdn.net/niushuai666/article/de ...

  8. 深入java并发Lock一

    java有像syncronized这种内置锁,但为什么还须要lock这种外置锁? 性能并非选择syncronized或者lock的原因,jdk6中syncronized的性能已经与lock相差不大. ...

  9. 如何禁止使用teamviwer的使用

    前几天有人问我teamviwer怎么禁止,刚开始做实验的时候过滤了teramviwer.com解析出来的IP,可是还是没有用,其实将teamviwer登陆的服务器地址在路由器上过滤,teramviwe ...

  10. Django写的投票系统4(转)

    原文地址:http://www.cnblogs.com/djangochina/archive/2013/06/04/3114269.html 现在已经可以在后台管理投票了,现在就差怎么在前台显示和如 ...