IOS开发-UI学习-sqlite数据库的操作

时间:2023-03-08 20:36:18
IOS开发-UI学习-sqlite数据库的操作

IOS开发-UI学习-sqlite数据库的操作

  sqlite是一个轻量级的数据库,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了,而且它的处理速度比Mysql、PostgreSQL这两款著名的数据库都还快,在ios和安卓app中常用来完成对数据进行离线缓存的处理,如新闻数据的离线缓存。

它的基本操作步骤是:

1、先加入sqlite开发库libsqlite3.dylib,

2、新建或打开数据库,

3、创建数据表,

4、插入数据,

5、查询数据并打印,

6、关闭数据库,

具体操作步骤如下:

1、导入sqlite数据库所需头文件:

导入完成后如图所示:

IOS开发-UI学习-sqlite数据库的操作

2、程序代码的编制:

 //
// ViewController.m
// sqlite手动创建数据库和表
//
// Created by mac on 16/4/12.
// Copyright © 2016年 mzw. All rights reserved.
// #import "ViewController.h"
#import "FMDatabase.h"
@interface ViewController (){
FMDatabase *mydb;
NSString * idd;
NSString * age;
NSString * name;
} @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; // 创建一个数据库路径path
NSString *path =[NSHomeDirectory() stringByAppendingString:@"/Documents/mydb.sqlite"]; // 根据创建好的路径path生成数据库
mydb = [[FMDatabase alloc]initWithPath:path]; // 创建一个在数据库中创建表mytable的字符串
NSString *tablecreate = @"create table if not exists mytable(id txt primary key,name text,age text)"; // 打开数据库
if ([mydb open]) { // 使用创建好的字符串新建表mytable
BOOL createOK = [mydb executeUpdate:tablecreate]; if (createOK) {
// 如果创建成果,打印创建成功的提示
NSLog(@"数据库创建成功"); // 使用sql语句中的insert into语句往创建好的mytable中添加一条记录
BOOL insertOK = [mydb executeUpdate:@"insert into mytable(id,age,name) values(?,?,?)",@"",@"",@"huangweiqiang"]; // 使用sql语句中的insert into语句往创建好的mytable中添加多条记录
BOOL insertsOK = [mydb executeUpdate:@"insert into mytable(id,age,name) select '2','24','mazhongwei' union all select '3','21','xiangyiyao' union all select '4','34','zhanglong'"]; // 使用sql语句中的delete from语句删除符合条件的语句
[mydb executeUpdate:@"delete from mytable where id = '4'"]; // 使用sql语句中的update更新表中的记录
[mydb executeUpdate:@"update mytable set age = '100000' where id = '3'"]; // 使用sql语句中的查询语句查询符合条件的语句,返回结果为一个集合,使用next函数遍历结果并赋值给idd,age,name三个变量
FMResultSet *rsset = [mydb executeQuery:@"select * from mytable where id = '3'"];
while ([rsset next]) {
idd = [rsset stringForColumn:@"id"];
age = [rsset stringForColumn:@"age"];
name = [rsset stringForColumn:@"name"];
} // 操作完成后关闭数据库
[mydb close]; // 打印查询结果
NSLog(@"%@_%@_%@",idd,age,name); }else{
// 如果创建失败,返回失败提示
NSLog(@"数据库创建失败");
}
} } @end