本文是主要实现了三个函数:

  •   testSQLite3 是测试系统自带的sqlite3的demo
  •   testFMDB是测试FMDB存取简单的数据类型的 的demo
  •   testFMDB2是将任意对象作为一个整体存入到FMDB的Demo

  首先先定义了一个Person类,实现了<NSCoding>协议,对Person对象进行字段存取和整体存取

 //Person.h
#import <Foundation/Foundation.h> @interface Person : NSObject<NSCoding>
@property (nonatomic ,assign)int id;
@property (nonatomic ,copy) NSString *name;
@property (nonatomic ,assign)int age;
@end //Person.m
#import "Person.h" @implementation Person
-(NSString *)description{
return [NSString stringWithFormat:@"id:%d--name:%@--age:%d",self.id,self.name,self.age];
}
-(instancetype)initWithCoder:(NSCoder *)decoder{
if (self = [super init]) {
self.id = [decoder decodeIntForKey:@"id"];
self.name = [decoder decodeObjectForKey:@"name"];
self.age = [decoder decodeIntForKey:@"age"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)encoder{
[encoder encodeInt:self.id
forKey:@"id"];
[encoder encodeObject:self.name forKey:@"name"];
[encoder encodeInt:self.age forKey:@"age"];
}
@end

Person

 -(void)testSQLite3{
//1. 打开(建立)数据库
NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filename = [cacheDir stringByAppendingPathComponent:@"test.sqlite"];
sqlite3 * db = nil; //0表示成功,1表示失败
sqlite3_open(filename.UTF8String, &db);
if (!db) {
NSLog(@"数据库打开失败,建立失败");
return;
}
char *errmsg = nil;
//2.一般用来执行无返回结果的sql 命令,(可以执行任何SQL语句)
//创建数据库
char * createTableSql = "create table t_person(id integer primary key,name text not null unique,age integer);";
int rs = sqlite3_exec(db, createTableSql, NULL, NULL, &errmsg); if (errmsg) {
NSLog(@"%s--errorCode:%d",errmsg,rs);
}
//3.插入数据
for(NSUInteger i = ;i < ;i ++){
NSString *insertSql = [NSString stringWithFormat:@"insert into t_person(name,age) values('小hong%lu',%d);",(unsigned long)i,arc4random()%+];
char *errmsg = nil;
sqlite3_exec(db, insertSql.UTF8String, NULL, NULL, &errmsg);
if (errmsg) {
NSLog(@"insert error:%s",errmsg);
}
}
//4.查询数据 尽量使用const char * 不要用NSString ,容易出错
const char* selectSql = "select * from t_person where name like '小明%' and age < 20 order by age desc limit 1,10";
sqlite3_stmt * stmt = nil;
sqlite3_prepare(db, selectSql, (int)strlen(selectSql), &stmt, NULL);
if (stmt) {
while (sqlite3_step(stmt) == SQLITE_ROW) {
Person *person = [[Person alloc]init];
person.id = sqlite3_column_int(stmt, );
person.name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, )];
person.age = sqlite3_column_int(stmt, );
NSLog(@"%@",person);
}
}

testSQLite3

 -(void)testFMDB{
NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filename = [cacheDir stringByAppendingPathComponent:@"new.sqlite"];
//1.建立数据库对象,一个数据库对应一个数据库对象
FMDatabase * db = [FMDatabase databaseWithPath:filename];
//2.打开数据库
if (![db open]) {
NSLog(@"数据库连接或者创建失败");
return;
}
//3. 建表
NSString *createSql = @"create table if not exists t_person(id integer primary key,name text not null unique,age integer);";
if (![db executeUpdate:createSql]) {
NSLog(@"error:%@",[db lastErrorMessage]);
}
//4.插入数据
for (int i = ; i< ; i++) {
//fmdb 最好自己把你的sql字符串用NSString写出来
NSString * insertSql = [NSString stringWithFormat:@"insert into t_person(name,age) values('xiaoming%d',%d)",i,arc4random()%];
if (![db executeUpdate:insertSql]) {
NSLog(@"error:%@",[db lastErrorMessage]);
}
}
//5.修改数据
NSString *updateStr = [NSString stringWithFormat:@"update t_person set age = 1000"];
if (![db executeUpdate:updateStr]) {
NSLog(@"error:%@",[db lastErrorMessage]);
}
//6. 删除数据
NSString *deleteStr= [NSString stringWithFormat:@"delete from t_person where id =1;"];
if (![db executeUpdate:deleteStr]) {
NSLog(@"error:%@",[db lastErrorMessage]);
}
//7.查询数据
NSString *querySql = [NSString stringWithFormat:@"select * from t_person"];
FMResultSet * set = [db executeQuery:querySql];
while (set.next) {
Person *person = [[Person alloc]init];
person.id = [set intForColumn:@"id"];
person.name = [set stringForColumn:@"name"];
person.age = [set intForColumn:@"age"];
NSLog(@"%@",person);
}
}

testFMDB

 //存取任意对象
-(void)testFMDB2{
NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filename = [cacheDir stringByAppendingPathComponent:@"Person.sqlite"];
//1.建立数据库对象,一个数据库对应一个数据库对象
FMDatabase * db = [FMDatabase databaseWithPath:filename];
//2.打开数据库
if (![db open]) {
NSLog(@"数据库连接或者创建失败");
return;
}
//3. 建表
NSString *createSql = @"create table if not exists t_persons(id integer primary key,person blob not null unique,age integer);";
if (![db executeUpdate:createSql]) {
NSLog(@"error:%@",[db lastErrorMessage]);
}
//4.插入数据
for (int i = ; i< ; i++) {
//将对象作为一个整体存入到数据库中
Person *person = [[Person alloc]init];
person.name = [NSString stringWithFormat:@"xiaoming%d",i];
person.age = arc4random()%;
person.id = arc4random();
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:person];
//插入blob 数据一定要使用excuteUpdateWithFormat:, 直接用executeUpdate:会报错的,因为你的数据使用NSLog打印出来会带有<>符号
if (![db executeUpdateWithFormat:@"insert into t_persons(person,age) values(%@,%d)",data,person.age]) {
NSLog(@"error:%@",[db lastErrorMessage]);
}
}
//5.修改数据
NSString *updateStr = [NSString stringWithFormat:@"update t_persons set age = 1000"];
if (![db executeUpdate:updateStr]) {
NSLog(@"error:%@",[db lastErrorMessage]);
}
//6. 删除数据
NSString *deleteStr= [NSString stringWithFormat:@"delete from t_persons where id =1;"];
if (![db executeUpdate:deleteStr]) {
NSLog(@"error:%@",[db lastErrorMessage]);
}
//7.查询数据
NSString *querySql = [NSString stringWithFormat:@"select * from t_persons "];
FMResultSet * set = [db executeQuery:querySql];
while (set.next) {
NSData *data = [set dataForColumn:@"person"];
// NSLog(@"%@",data);
Person *person = [NSKeyedUnarchiver unarchiveObjectWithData:data];
person.id = [set intForColumn:@"id"];
NSLog(@"%@",person);
} }

testFMDB2

iOS Sqlite3 Demo 及 FMDB Demo的更多相关文章

  1. IOS CoreData 多表查询demo解析

    在IOS CoreData中,多表查询上相对来说,没有SQL直观,但CoreData的功能还是可以完成相关操作的. 下面使用CoreData进行关系数据库的表与表之间的关系演示.生成CoreData和 ...

  2. iOS活体人脸识别的Demo和一些思路

    代码地址如下:http://www.demodashi.com/demo/12011.html 之前公司项目需要,研究了一下人脸识别和活体识别,并运用免费的讯飞人脸识别,在其基础上做了二次开发,添加了 ...

  3. iOS 数据库操作(使用FMDB)

    iOS 数据库操作(使用FMDB)   iOS中原生的SQLite API在使用上相当不友好,在使用时,非常不便.于是,就出现了一系列将SQLite API进行封装的库,例如FMDB.Plausibl ...

  4. 在iOS开发中使用FMDB

    在iOS开发中使用FMDB 前言 SQLite (http://www.sqlite.org/docs.html) 是一个轻量级的关系数据库.iOS SDK 很早就支持了 SQLite,在使用时,只需 ...

  5. 【转】在iOS开发中使用FMDB

    本文转载自:唐巧的博客 在iOS开发中使用FMDB APR 22ND, 2012 前言 SQLite (http://www.sqlite.org/docs.html) 是一个轻量级的关系数据库.iO ...

  6. iOS sqlite3 的基本使用(增 删 改 查)

    iOS sqlite3 的基本使用(增 删 改 查) 这篇博客不会讲述太多sql语言,目的重在实现sqlite3的一些基本操作. 例:增 删 改 查 如果想了解更多的sql语言可以利用强大的互联网. ...

  7. iOS开发数据库篇—FMDB简单介绍

    iOS开发数据库篇—FMDB简单介绍 一.简单说明 1.什么是FMDB FMDB是iOS平台的SQLite数据库框架 FMDB以OC的方式封装了SQLite的C语言API 2.FMDB的优点 使用起来 ...

  8. iOS开发数据库篇—FMDB数据库队列

    iOS开发数据库篇—FMDB数据库队列 一.代码示例 1.需要先导入FMDB框架和头文件,由于该框架依赖于libsqlite库,所以还应该导入该库. 2.代码如下: // // YYViewContr ...

  9. [iOS]数据库第三方框架FMDB详细讲解

    [iOS]数据库第三方框架FMDB详细讲解 初识FMDB iOS中原生的SQLite API在进行数据存储的时候,需要使用C语言中的函数,操作比较麻烦.于是,就出现了一系列将SQLite API进行封 ...

随机推荐

  1. Internship

    zoj2532:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1532 题意:有n个发射点,m个中继站,然后发射点会发射一些信息 ...

  2. gridview数据导出到word和excel以及excel的导入

    using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI ...

  3. 【HDOJ】3183 A Magic Lamp

    RMQ. /* 3183 */ #include <cstdio> #include <cstring> #include <cstdlib> #define MA ...

  4. Fixing common issues when hosting a .NET 4.0 WCF service in IIS 7

    http://sandrinodimattia.net/fixing-common-issues-when-hosting-a-net-4-0-wcf-service-in-iis-7/ Until ...

  5. makefile 自动处理头文件的依赖关系 (zz)

    现在我们的Makefile写成这样: all: main main: main.o stack.o maze.ogcc $^ -o $@ main.o: main.h stack.h maze.hst ...

  6. (转载)用PHP实现翻页

    (转载)http://blog.csdn.net/emili/article/details/5221744 原文参考http://www.cnblogs.com/xxcainiao/archive/ ...

  7. implicitly_wait()隐式等待

    # -*- coding:utf-8 -*- """ implicitly_wait():隐式等待 当使用了隐士等待执行测试的时候,如果 WebDriver没有在 DOM ...

  8. Web Services的相关名词解释:WSDL与SOAP

    在对Web Services进行性能测试时,接触到最多的两个名词就是WSDL和SOAP.利用LoadRunner对Web Services进行调用的时候,也存在两种常用方法,即基于WSDL的[Add ...

  9. Perfect Squares——Leetcode

    Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 1 ...

  10. java 泛型学习

    http://blog.csdn.net/archie2010/article/details/6232228 学习集合框架的时候经常用hasmap<Integer,Integer>就是泛 ...