在工程里导入libsqlite3.tbd库(Xcode 7)

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end
#import "AppDelegate.h"
#import "RootViewController.h"
@interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor]; self.window.rootViewController = [[RootViewController alloc] init]; [self.window makeKeyAndVisible];
return YES;
} @end
#import <UIKit/UIKit.h>

@interface RootViewController : UIViewController

@end
#import "RootViewController.h"
#import "Goods.h"
#import "Company.h"
#import "Infomation.h" @interface RootViewController () @end @implementation RootViewController - (void)viewDidLoad {
[super viewDidLoad];
Goods *goods1 = [[Goods alloc] init];
goods1.name = @"奥利";
goods1.size = ;
goods1.color = @"blue"; Company *company1 = [[Company alloc] init];
company1.goods = goods1;
company1.name = @"影视有限公司";
company1.address = @"广州";
company1.numberOfPeople = ;
company1.rank = ; Goods *goods2 = [[Goods alloc] init];
goods2.name = @"好好";
goods2.size = ;
goods2.color = @"棕色"; Company *company2 = [[Company alloc] init];
company2.goods = goods2;
company2.name = @"食品有限公司";
company2.address = @"北京";
company2.numberOfPeople = ;
company2.rank = ; Infomation *info = [[Infomation alloc] init];
//数据如果没有创建,则创建(只创建一次)
if (![info createTable]) {
[info createTable];
}
// 插入数据
// [info add:company1 andGoodsOfCompany:company1.goods];
// [info add:company2 andGoodsOfCompany:company2.goods];
// 查询所有数据
// NSMutableArray *arr = [info getAllCompanyData];
//更新数据
// company2.name = @"广告股份有限公司";
// [info updateData:company2 andGoodsOfCompany:company2.goods];
// // 查询所有数据
// arr = [info getAllCompanyData];
// // 删除company2
// [info deleteData:company2 andGoodsOfCompany:company2.goods];
// 查询所有数据
// arr = [info getAllCompanyData];
// // 查询
// [info fineData:@"影视有限公司"];
// 删除所有
[info deleteAllData];
[info getAllCompanyData]; } - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end
#import <Foundation/Foundation.h>
@class Goods; @interface Company : NSObject @property(nonatomic, strong) NSString *name;
@property(nonatomic, strong) Goods *goods;
@property(nonatomic, assign) int numberOfPeople;
@property(nonatomic, strong) NSString *address;
@property(nonatomic, assign) int rank; @end
#import "Company.h"
#import "Goods.h"
@implementation Company @synthesize name;
@synthesize goods;
@synthesize numberOfPeople;
@synthesize address;
@synthesize rank; -(void)dealloc{
goods = nil;
address = nil;
name = nil;
} - (instancetype)init
{
self = [super init];
if (self) {
name = @"";
goods = [[Goods alloc] init];
address = @"";
}
return self;
} @end
#import <Foundation/Foundation.h>

@interface Goods : NSObject

@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) int size;
@property (nonatomic, strong) NSString *color; @end
#import "Goods.h"

@implementation Goods

@synthesize name;
@synthesize size;
@synthesize color; - (void)dealloc
{
name = nil;
color = nil;
} - (instancetype)init
{
self = [super init];
if (self) {
name = @"";
size = ;
color = @"";
}
return self;
} @end
#import <Foundation/Foundation.h>
#import <sqlite3.h> @interface BaseDB : NSObject /**
* 创建表
*/
- (void)createTable:(NSString *)sql; /**
*增删改
*/
- (void)dealData:(NSString *)sql paramarray:(NSArray *)params; /**
* 查询
*/
- (NSMutableArray *)selectData:(NSString *)sql withParams:(NSArray *)params withColumns:(int)columns; @end
#import "BaseDB.h"

#define kFileName @"test.sqlite"

@interface BaseDB ()
{
sqlite3 *database;
}
@end @implementation BaseDB // 数据库文件路径
- (NSString *)dataFilePath{
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSLog(@"数据库的路径为:%@",path);
return [path stringByAppendingPathComponent:kFileName];
} // 创建表
-(void)createTable:(NSString *)sql{
//防止self对象在同一时间内被其它线程访问,起到线程的保护作用
@synchronized(self) {
//打开数据库,这里的[path UTF8String]是将NSString转换为C字符串,因为SQLite3是采用可移植的C(而不是Objective-C)编写的,它不知道什么是NSString.
if (sqlite3_open([[self dataFilePath] UTF8String], &database) != SQLITE_OK) {
NSLog(@"数据库打开失败");
//如果打开数据库失败则关闭数据库
sqlite3_close(database);
} char *errorMsg;
// 执行非查询的sql语句
if (sqlite3_exec(database, [sql UTF8String], NULL, NULL, &errorMsg)!= SQLITE_OK) {
NSLog(@"创建表失败:%s",errorMsg);
// 关闭数据库
sqlite3_close(database);
}
}
} // 增删改
- (void)dealData:(NSString *)sql paramarray:(NSArray *)params{
[self selectData:sql withParams:params withColumns:];
} // 查询
- (NSMutableArray *)selectData:(NSString *)sql withParams:(NSArray *)params withColumns:(int)columns{
NSMutableArray *returndata = [[NSMutableArray alloc] init];
//防止self对象在同一时间内被其它线程访问,起到线程的保护作用
@synchronized(self) { if (sqlite3_open([[self dataFilePath] UTF8String], &database) == SQLITE_OK) {
//相当于ODBC的Command对象,用于保存编译好的SQL语句
sqlite3_stmt *statement = nil; //sqlite3_prepare_v2 接口把一条SQL语句解析到statement结构里去. 使用该接口访问数据库是当前比较好的的一种方法
//第一个参数跟前面一样,是个sqlite3 * 类型变量,
//第二个参数是一个 sql 语句。
//第三个参数我写的是-1,这个参数含义是前面 sql 语句的长度。如果小于0,sqlite会自动计算它的长度(把sql语句当成以\0结尾的字符串)。
//第四个参数是sqlite3_stmt 的指针的指针。解析以后的sql语句就放在这个结构里。
//第五个参数是错误信息提示,一般不用,为nil就可以了。
//如果这个函数执行成功(返回值是 SQLITE_OK 且 statement 不为NULL ),那么下面就可以开始插入二进制数据。
if (sqlite3_prepare_v2(database, [sql UTF8String], -, &statement, NULL) == SQLITE_OK) {
if (params != nil && params.count != ) {
for (int i = ; i < params.count; i++) {
NSString *tmp = nil;
// 取出参数
id param = [params objectAtIndex:i];
// 判断参数的类型
if ([param isKindOfClass:[NSNumber class]]) {
// 转成字符串类型
tmp = [param stringValue];
}else{
tmp = param;
}
//这里的数字i+1代表values的第几个值(从1开始)
sqlite3_bind_text(statement, i+, [tmp UTF8String], -, SQLITE_TRANSIENT);
}
}
//在调用sqlite3_prepare后,使用这个函数在记录集中移动。
int result = sqlite3_step(statement);
if (columns != ) {
// SQLITE_ROW: 返回一行结果
while (result == SQLITE_ROW) {
NSMutableArray *data = [[NSMutableArray alloc] init];
for (int i = ; i < columns; i++) {
//这里的数字i对应的是数据库第几列的值(从零开始)
char *contentchar = (char *)sqlite3_column_text(statement, i);
if (contentchar) {
[data addObject:[NSString stringWithCString:contentchar encoding:NSUTF8StringEncoding]];
}else{
[data addObject:@""];
}
}
[returndata addObject:data];
//qlite3_step返回SQLITE_ROW,可以得到列数
result = sqlite3_step(statement);
}
}
}
//清理statement对象
sqlite3_finalize(statement);
}
sqlite3_close(database);
}
return returndata;
} @end
#import "BaseDB.h"
@class Company;
@class Goods;
@interface Infomation : BaseDB /**
* 创建数据表格
*/
- (BOOL)createTable; /**
* 添加数据
*/
- (void)add:(Company *)aCompany andGoodsOfCompany:(Goods*)goodsFromCompany; /**
* 删除全部数据
*/
- (void)deleteAllData; /**
* 获取所有数据
*/
- (NSMutableArray *)getAllCompanyData; /**
* 更新数据
*/
- (void)updateData:(Company *)aCompany andGoodsOfCompany:(Goods*)goodsFromCompany; /**
* 查询数据
*/
- (NSMutableArray *)fineData:(NSString *)nameOfCompany; /**
* 删除数据
*/
- (void)deleteData:(Company *)aCompany andGoodsOfCompany:(Goods*)goodsFromCompany; @end
#import "Infomation.h"
#import "Company.h"
#import "Goods.h" @implementation Infomation //将数据转化成模型数据
- (NSMutableArray *)changeToModelDataWithArray:(NSArray *)dataArray{
NSMutableArray *data = [NSMutableArray array];
for (int i = ; i < dataArray.count; i++) {
NSArray *array = [dataArray objectAtIndex:i];
Company *company = [[Company alloc] init];
Goods *goods = [[Goods alloc] init];
company.name = array[];
company.address = array[];
company.numberOfPeople = [array[] intValue];
NSLog(@"====%@",array[]);
company.rank = [array[] intValue];
goods.name = array[];
goods.size = [array[] intValue];
goods.color = array[];
company.goods = goods;
NSLog(@"%@--%d--%@--%@--%@--%d--%d",company.goods.name,company.goods.size,company.goods.color,company.name,company.address,company.numberOfPeople,company.rank);
}
return data;
} // 创建列表
- (BOOL)createTable{ NSString *sql = @"create table if not exists CompanyTable( name varchar(50), address varchar(50), numberOfPeolpe int, rank int, nameOfGoods varchar(50), sizeOfGoods int, colorOfGoods varchar(20))";
[self createTable:sql];
return YES;
} - (void)add:(Company *)aCompany andGoodsOfCompany:(Goods*)goodsFromCompany{
NSString *sql = @"insert into CompanyTable(name,address,numberOfPeolpe,rank,nameOfGoods,sizeOfGoods,colorOfGoods) values (?,?,?,?,?,?,?)"; NSArray *params = [NSArray arrayWithObjects:aCompany.name,aCompany.address,@(aCompany.numberOfPeople) ,@(aCompany.rank) ,goodsFromCompany.name,@(goodsFromCompany.size),goodsFromCompany.color, nil];
[self dealData:sql paramarray:params];
} // 删除全部数据
- (void)deleteAllData{
NSString *sql = @"delete from CompanyTable";
[self dealData:sql paramarray:nil];
} // 获取所有数据
- (NSMutableArray *)getAllCompanyData{
NSString *sql = @"select name,address,numberOfPeolpe,rank,nameOfGoods,sizeOfGoods,colorOfGoods from CompanyTable";
NSMutableArray *arr = [self selectData:sql withParams:nil withColumns:];
NSMutableArray *backData = [self changeToModelDataWithArray:arr];
return backData;
} // 更新数据
- (void)updateData:(Company *)aCompany andGoodsOfCompany:(Goods*)goodsFromCompany{
NSString *sql = @"replace into CompanyTable(name,address,numberOfPeolpe,rank,nameOfGoods,sizeOfGoods,colorOfGoods) values (?,?,?,?,?,?,?)";
NSArray *params = [NSArray arrayWithObjects:aCompany.name,aCompany.address,@(aCompany.numberOfPeople) ,@(aCompany.rank) ,goodsFromCompany.name,@(goodsFromCompany.size),goodsFromCompany.color, nil];
[self dealData:sql paramarray:params];
} // 查询数据
- (NSMutableArray *)fineData:(NSString *)nameOfCompany{
NSString *sql = [NSString stringWithFormat:@"select * from CompanyTable where name like \"%@\"",nameOfCompany];
NSMutableArray *arr = [self selectData:sql withParams:nil withColumns:];
NSMutableArray *backData = [self changeToModelDataWithArray:arr];
return backData;
} // 删除数据
- (void)deleteData:(Company *)aCompany andGoodsOfCompany:(Goods*)goodsFromCompany{
NSString *sql = @"delete from CompanyTable where name = ? and address = ? and numberOfPeolpe = ?and rank = ? and nameOfGoods = ? and sizeOfGoods = ? and colorOfGoods = ?";
NSArray *params = [NSArray arrayWithObjects:aCompany.name,aCompany.address,@(aCompany.numberOfPeople) ,@(aCompany.rank) ,goodsFromCompany.name,@(goodsFromCompany.size),goodsFromCompany.color, nil];
[self dealData:sql paramarray:params];
} @end

iOS SQLite 增删改查的封装(关系型)的更多相关文章

  1. iOS sqlite 增删改查 简单封装(基于 FMDB)

    /** *  对 sqlite 的使用进行简单封装,仅涉及简单的单表 增删改查 * *  基于 FMDB * *  操作基于 model ,数据库表字段与 model 属性一一对应,对 model 整 ...

  2. iOS SQLite增删改查(简单应用)

    // 注意: 在工程里导入libsqlite3.tbd库(Xcode7,如果Xcode7以下的版本则导入libsqlite3.dylib). #import <UIKit/UIKit.h> ...

  3. android 入门 006(sqlite增删改查)

    android 入门 006(sqlite增删改查) package cn.rfvip.feb_14_2_sqlite; import android.content.Context; import ...

  4. iOS CoreData 增删改查详解

    最近在学习CoreData, 因为项目开发中需要,特意学习和整理了一下,整理出来方便以后使用和同行借鉴.目前开发使用的Swift语言开发的项目.所以整理出来的是Swift版本,OC我就放弃了. 虽然S ...

  5. jdbc增删改查进行封装

    jdbc封装 1 dao (代码分层) com.aaa.dao 存放dao相关的类型 例如 StudentDAOImpl 处理 数据库的链接 存取数据 com.aaa.servlet 存放servle ...

  6. C#Sqlite增删改查

    说到使用数据库的话,无非也就是对数据的增加,删除和修改以及查询.前文已经 创建好了程序,现在我们就可以来具体实现Sqlite的数据操作,增删改查. 第一步,创建连接字符串来连接数据库: private ...

  7. [IOS]包含增删改查移动的tableView展示+plist文件保存+程序意外退出保存Demo

    做一个tableView,包含增删改移动功能,并且修改值的时候,在按home键的时候会自动保存.如果可以的话使者保存自定义的类数组保存到plist中. 实现步骤: 1.创建一个SingleViewAp ...

  8. 回家前的挣扎——SQLite增删改查

    引言 最后一天,公司就两个人,也不知道弄点什么,就在网上找了Sqlite的文档,看了看,这里也是现学现卖,给自己找点事做,感觉时间过得还是比较快的,不然焦急等待,滋味不好受啊. SQLite简介 SQ ...

  9. C# 使用 Dapper 实现 SQLite 增删改查

    Dapper 是一款非常不错的轻型 ORM 框架,使用起来非常方便,经常使用 EF 框架的人几乎感觉不到差别,下面是自己写的 Sqlite 通用帮助类: 数据连接类: public class SQL ...

随机推荐

  1. jQuery 复合选择器的几个例子

    <!-- 本文例子所引用的jQuery版本为 jQuery-1.8.3.min.js Author:博客园小dee --> 一. 复合选择器对checkbox的相关操作 1 <inp ...

  2. UITextField里面的 placeholder颜色和字体

    //  placeholder 颜色 [field setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor& ...

  3. Unity4.5版本DLL库名字问题

      背景 在unity4.2版本中可以在Android中使用的so链接库,在Unity4.5中使不了-- [DllImport("libclient.so", EntryPoint ...

  4. Rails--%w用法[转]

    %Q 用于替代双引号的字符串. 当你需要在字符串里放入很多引号时候, 可以直接用下面方法而不需要在引号前逐个添加反斜杠 (\") >> %Q(Joe said: "Fr ...

  5. memcached学习笔记5--socke操作memcached 缓存系统

    使用条件:当我们没有权限或者不能使用服务器的时候,我们需要用socket操作memcached memcached-client操作 特点: 无需开启memcache扩展 使用fsocketopen( ...

  6. [转]通过Mesos、Docker和Go,使用300行代码创建一个分布式系统

    http://www.csdn.net/article/2015-07-31/2825348 [编者按]时下,对于大部分IT玩家来说,Docker和Mesos都是熟悉和陌生的:熟悉在于这两个词无疑已成 ...

  7. Diode

    Diode https://zh.wikipedia.org/wiki/真空管 抽真空 电子在于其放射过程中,因会与空气中之组成分子相撞而产生阻力,因此电子经由如空气之类的介质来移动的话,将会比在真空 ...

  8. Delphi 记录类型- 结构指针

    unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms ...

  9. android Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine.

    在当前工程目录中 gradle.properties 添加org.gradle.jvmargs=-XX\:MaxHeapSize\=256m -Xmx256m http://stackoverflow ...

  10. 【转】Unity3D开发之Http协议网络通信

    之前unity3d项目要做跟服务器通信的模块,然后服务器那边的协议是基于http的Jsonrpc通信方式一开始,用C#的本身类HttpWebRequest来提交请求,很快就在电脑上面成功了,代码也很简 ...