当前位置: 移动技术网 > IT编程>移动开发>IOS > IOS开发(94)之SQLite数据库

IOS开发(94)之SQLite数据库

2019年05月12日  | 移动技术网IT编程  | 我要评论

sqlite是mysql的简化版,更多的运用与移动设备或小型设备上。sqlite的优点是具有可移植性,它不需要服务器就能运行,同时,它也存在一些缺陷,首先,没有提供简单的创建方式,必须手工创建数据库,其次,sqlite没有面向对象接口,必须使用依赖于c语言代码的api。相对于oc,这套api既不那么优雅,也更难使用。当相比于用文件进行存储,还是更推荐使用sqlite进行数据存储。

 


下面来看下如何使用sqlite

 


工程目录如下:

 

\

首先建立一个single view application工程,命名为sqlite3test,然后打开viewcontroller.xib文件,布局如下,并设置三个uitextfield的tag分别为1、2、3

 

\

设置tag的地方在属性选择器中(xcode右边)

 

 \
 

 

然后在viewcontroller.h文件中声明如下:


[cpp]
<span style="font-family:comic sans ms;font-size:18px;">#import <uikit/uikit.h> 
@interface viewcontroller : uiviewcontroller 
@property(copy,nonatomic) nsstring *databasefilepath; 
//这个方法定义的是当应用程序退到后台时将执行的方法,按下home键执行(通知中心来调度) 
-(void)applicationwillresignactive:(nsnotification *)notification; 
//当通过键盘在uitextfield中输入完毕后,点击屏幕空白区域关闭键盘的操作 
-(ibaction)backgroundtapped:(id)sender; 
@end</span> 

 

接下来看下.m文件的具体实现,就不一一介绍了,在代码中会有注释

在开始写代码前,要导入sqlite支持包 libsqlite3.dylib(具体做法就不详述了)

上代码:


[cpp]
#import "viewcontroller.h" 
#import "sqlite3.h" 
//数据库文件的名字 
#define kdatabasename @"database.sqlite3" 
 
@interfaceviewcontroller () 
 
@end 
 
@implementation viewcontroller 
 
@synthesize databasefilepath; 
 
- (void)viewdidload 

    [superviewdidload]; 
     
    nsarray *path = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes); 
    nsstring *documentdirectory = [path objectatindex:0]; 
    //指定数据库文件的路径 
    self.databasefilepath = [documentdirectory stringbyappendingpathcomponent:kdatabasename]; 
     
    //打开数据库 
    sqlite3 *database; 
    //[self.databasefilepath utf8string];将oc字符串装换成c字符串 
    if (sqlite3_open([self.databasefilepathutf8string], &database) != sqlite_ok) { 
        //关闭数据库 
        sqlite3_close(database); 
        nsassert(0,@"数据库打开失败"); 
    } 
         
    //创建表格 
    nsstring *createsql = @"create table if not exists student (tag integer primary key ,field_data text);"; 
    //若发生错误,则错误信息存在该字符串中 
    char *errormsg; 
     
    //sqlite3_exec这个方法可以执行那些没有返回结果的操作,例如创建、插入、删除等,这个函数包含了sqlite3_prepare这个函数的操作,目的是将utf-8格式的sql语句转换为编译后的语句 
    if (sqlite3_exec(database, [createsql utf8string], null, null, &errormsg) != sqlite_ok) { 
        sqlite3_close(database); 
        nsassert(0,@"创建表错误:%s", errormsg); 
    } 
     
    //查询数据库 
    nsstring *querysql = @"select * from student order by tag"; 
    //语句句柄 
    sqlite3_stmt *statament; 
    //sqlite3_prepare_v2的作用是将utf-8格式的sql语句转换为编译后的语句,并返回指向该语句的指针 
    if (sqlite3_prepare_v2(database, [querysql utf8string], -1, &statament, nil) == sqlite_ok) { 
        //sqlite3_step的作用是在编译后的语句中向前移动一条记录,sqlite_row代表一行 
        while (sqlite3_step(statament) == sqlite_row) { 
            //返回当前这条记录中的一个int类型字段的值,下面sqlite3_column_text返回一个字符串类型的值,后面的数字对应每一列 
            int tag = sqlite3_column_int(statament, 1); 
            char *rowdata = (char *)sqlite3_column_text(statament, 2); 
            //如果要得到一个nsstring字符串,可以采用如下方法 
            //nsstring *str = [nsstring stringwithutf8string:(char *)sqlite3_column_text(statament, 1)]; 
             
            //通过tag得到ui控件,类似android中的findviewbyid(id) 
            uitextfield *textfield = (uitextfield *)[self.viewviewwithtag:tag]; 
             
            //[[nsstring alloc]initwithutf8string:rowdata] 将c字符串转换成oc字符串 
            textfield.text = [[nsstringalloc]initwithutf8string:rowdata]; 
        } 
        //删除编译后的语句 
        sqlite3_finalize(statament); 
    } 
    sqlite3_close(database); 
     
    //注册通知,当程序将要退到后台时执行applicationwillresignactive方法(在.h中定义) 
    uiapplication *application = [uiapplicationsharedapplication]; 
    [[nsnotificationcenterdefaultcenter] addobserver:selfselector:@selector(applicationwillresignactive:) name:uiapplicationwillresignactivenotificationobject:application]; 

 
- (void)viewdidunload 

    [superviewdidunload]; 
    // release any retained subviews of the main view. 

 
- (bool)shouldautorotatetointerfaceorientation:(uiinterfaceorientation)interfaceorientation 

    return (interfaceorientation != uiinterfaceorientationportraitupsidedown); 

 
//按下home键程序将要进入后台前保存uitextfield中的数据 
-(void)applicationwillresignactive:(nsnotification *)notification 

    sqlite3 *database; 
    if (sqlite3_open([self.databasefilepathutf8string], &database) != sqlite_ok) { 
        nsassert(0,@"打开数据库错误"); 
        sqlite3_close(database); 
    } 
     
    for (int i = 1; i <= 3; i++) { 
        uitextfield *textfield = (uitextfield *)[self.viewviewwithtag:i]; 
         
        //插入数据 
        char *update = "insert or replace into student values (?,?)"; 
        sqlite3_stmt *statement; 
        if (sqlite3_prepare_v2(database, update, -1, &statement, nil) == sqlite_ok) { 
            //将值保存到指定的列 
            sqlite3_bind_int(statement, 1, i); 
             
            //第四个参数代表第三个参数中需要传递的长度。对于c字符串来说,-1表示传递全部字符串。第五个参数是一个回调函数,比如执行后做内存清除工作。 
            sqlite3_bind_text(statement, 2, [textfield.textutf8string], -1, null); 
        } 
         
        char *errormsg = null; 
        //sqlite_done代表更新数据库是否完成 
        if (sqlite3_step(statement) != sqlite_done) { 
            nsassert(0,@"更新数据出错:%s",errormsg); 
        } 
        sqlite3_finalize(statement); 
    } 
     
    sqlite3_close(database); 

 
-(ibaction)backgroundtapped:(id)sender 

    /*当通过键盘在uitextfield中输入完毕后,点击屏幕空白区域关闭键盘的操作
     设置步骤是打开.xib文件选中整个视图,然后将属性选择器中的class由uiview改成uicontrol,然后在事件选取器中选择touch down事件并连线到.h文件中的backgroundtapped方法
     */ 
    for (int i = 1; i <= 3; i ++) { 
        uitextfield *textfield = (uitextfield *)[self.viewviewwithtag:i]; 
        [textfield resignfirstresponder]; 
    } 

 
@end 


最后运行效果如下,输入信息后按下home键,然后再进入应用,可以看到数据在每次退出前都保存了,再次进入则从sqlite数据库查询保存的数据并显示在界面上

 

\

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

  • ios uicollectionview实现横向滚动

    现在使用卡片效果的app很多,之前公司让实现一种卡片效果,就写了一篇关于实现卡片的文章。文章最后附有demo实现上我选择了使用uicollectionview ... [阅读全文]
  • iOS UICollectionView实现横向滑动

    本文实例为大家分享了ios uicollectionview实现横向滑动的具体代码,供大家参考,具体内容如下uicollectionview的横向滚动,目前我使... [阅读全文]
  • iOS13适配深色模式(Dark Mode)的实现

    iOS13适配深色模式(Dark Mode)的实现

    好像大概也许是一年前, mac os系统发布了深色模式外观, 看着挺刺激, 时至今日用着也还挺爽的终于, 随着iphone11等新手机的发售, ios 13系统... [阅读全文]
  • ios 使用xcode11 新建项目工程的步骤详解

    ios 使用xcode11 新建项目工程的步骤详解

    xcode11新建项目工程,新增了scenedelegate这个类,转而将原appdelegate负责的对ui生命周期的处理担子接了过来。故此可以理解为:ios... [阅读全文]
  • iOS实现转盘效果

    本文实例为大家分享了ios实现转盘效果的具体代码,供大家参考,具体内容如下demo下载地址: ios转盘效果功能:实现了常用的ios转盘效果,轮盘抽奖效果的实现... [阅读全文]
  • iOS开发实现转盘功能

    本文实例为大家分享了ios实现转盘功能的具体代码,供大家参考,具体内容如下今天给同学们讲解一下一个转盘选号的功能,直接上代码直接看viewcontroller#... [阅读全文]
  • iOS实现轮盘动态效果

    本文实例为大家分享了ios实现轮盘动态效果的具体代码,供大家参考,具体内容如下一个常用的绘图,主要用来打分之类的动画,效果如下。主要是ios的绘图和动画,本来想... [阅读全文]
  • iOS实现九宫格连线手势解锁

    本文实例为大家分享了ios实现九宫格连线手势解锁的具体代码,供大家参考,具体内容如下demo下载地址:效果图:核心代码://// clockview.m// 手... [阅读全文]
  • iOS实现卡片堆叠效果

    本文实例为大家分享了ios实现卡片堆叠效果的具体代码,供大家参考,具体内容如下如图,这就是最终效果。去年安卓5.0发布的时候,当我看到安卓全新的material... [阅读全文]
  • iOS利用余弦函数实现卡片浏览工具

    iOS利用余弦函数实现卡片浏览工具

    本文实例为大家分享了ios利用余弦函数实现卡片浏览工具的具体代码,供大家参考,具体内容如下一、实现效果通过拖拽屏幕实现卡片移动,左右两侧的卡片随着拖动变小,中间... [阅读全文]
验证码:
移动技术网