创建一个类存储主键id
创建类
#import <Foundation/Foundation.h>
#import "ClassMessage.h"
@interface SqlData : NSObject
//单利方法
+(instancetype)initData;
//初始化数据库
-(void)initSql;
//初始化表格
-(void)initTable;
//添加数据
-(void)addData:(ClassMessage *)data;
//修改数据
-(void)upData:(ClassMessage *)data;
//删除数据
-(void)deleteData:(NSInteger )theid;
//查询数据
-(NSMutableArray *)array;
//关闭数据库
-(void)closeSql;
@end
.m里实现方法
/*
使用FMDB第三方框架 导入第三方框架
*/
#import "SqlData.h"
#import "FMDatabase.h"
#import "ClassMessage.h"
//创建静态变量
static SqlData *sqlData1;
static FMDatabase *db;
@implementation SqlData
//单利方法
+ (instancetype)initData{
if (!sqlData1) {
sqlData1 = [[SqlData alloc] init];
}
return sqlData1;
}
//初始化数据库
- (void)initSql{
//获取DOcuments目录
NSString *str = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
//拼接路径
NSString *fileName = [str stringByAppendingString:@"/strname.db"];
//创建数据库
db = [[FMDatabase alloc] initWithPath:fileName];
if ([db open]) {
NSLog(@"数据库打开成功");
//调用初始化表格方法
[self initTable];
}else{
NSLog(@"数据库打开失败");
}
}
//初始化表格
-(void)initTable{
//初始化数据库表格的格式:create table if not exists 表名(主键id integer primary key,所有的数据类型);
[db executeUpdate:@"create table ClassMessage(classid integer primary key,name text,age text,sex text)"];
//关闭数据库
[db close];
}
//添加数据
- (void)addData:(ClassMessage *)data{
if ([db open]) {
//添加数据的sql语句:insert into 表名 values(null,?,?);
[db executeUpdate:[NSString stringWithFormat:@"insert into ClassMessage values(null,'%@','%@','%@')",data.name,data.age,data.sex]];
}else{
NSLog(@"添加数据失败");
}
//关闭数据库
[db close];
}
//删除数据
- (void)deleteData:(NSInteger)theid{
//sql 语句: delete from 表名 where 表名的主键id = ?
if ([db open]) {
[db executeUpdate:[NSString stringWithFormat:@"delete from ClassMessage where classid = '%ld'",theid]];
}else{
NSLog(@"删除数据失败");
}
//关闭数据库
[db close];
}
//修改数据
- (void)upData:(ClassMessage *)data{
//sql 语句的格式:update 表名 set 所有数据 where 主键id = ?
if ([db open]) {
[db executeUpdate:[NSString stringWithFormat:@"update ClassMessage set name = '%@' ,age = '%@',sex = '%@' where classid = '%ld'",data.name,data.age,data.sex,data.classid]];
}else{
NSLog(@"修改数据失败");
}
//关闭数据库
[db close];
}
//查询数据
- (NSMutableArray *)array{
//创建数据
NSMutableArray *arr = [NSMutableArray array];
//集合
FMResultSet *set = [FMResultSet new];
if ([db open]) {
//sql 语句格式:select *from 表名
set = [db executeQuery:@"select *from ClassMessage"];
// 判断有没有查询到 一行一行去查询
while ([set next]) {
ClassMessage *msg = [[ClassMessage alloc] init];
msg.classid = [set intForColumn:@"classid"];
msg.name = [set stringForColumn:@"name"];
msg.age = [set stringForColumn:@"age"];
msg.sex = [set stringForColumn:@"sex"];
//将msg对象添加到数据
[arr addObject:msg];
}
}else{
NSLog(@"查询失败");
}
[db close];
return arr;
}
@end
VC里搭建表格布局
#import "ViewController.h"
#import "SecViewController.h"
#import "SqlData.h"
#import "ClassMessage.h"
@interface ViewController ()
{
NSMutableArray *array;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"数据库";
//右侧按钮
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(click)];
//设置行高
self.tableView.rowHeight = 100;
}
//视图即将显示的时候调用
- (void)viewWillAppear:(BOOL)animated{
//调用数据库单利方法
[[SqlData initData] initSql];
//调用查询数据方法
array = [[SqlData initData] array];
//刷新表格
[self.tableView reloadData];
}
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return array.count;
}
//设置cell内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
//创建classMessage对象
ClassMessage *classMsg = array[indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"%ld\n姓名:%@\n年龄:%@\n性别:%@",classMsg.classid,classMsg.name,classMsg.age,classMsg.sex];
cell.textLabel.numberOfLines = 0;
return cell;
}
//点击右侧按钮方法
-(void)click{
//跳转到第二个控制器
SecViewController *secVc = [SecViewController new];
[self.navigationController pushViewController:secVc animated:YES];
}
//点击单元格方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
SecViewController *secVc = [SecViewController new];
//属性传值
secVc.msg = array[indexPath.row];
[self.navigationController pushViewController:secVc animated:YES];
}
//让表格处于编辑状态 删除数据
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
[[SqlData initData]initSql];
//是删除主键id 获取数据库中的数据
[[SqlData initData]deleteData:[array[indexPath.row]classid]];
//删除数据
[array removeObject:array[indexPath.row]];
//刷新表格
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
第二个界面定义属性传值
#import <UIKit/UIKit.h>
#import "ClassMessage.h"
@interface SecViewController : UIViewController
@property(nonatomic,strong)ClassMessage *msg;
@end
.m定义保存修改方法
#import "SecViewController.h"
#import "ClassView.h"
#import "SqlData.h"
@interface SecViewController ()
{
ClassView *theView;
}
@end
@implementation SecViewController
- (void)viewDidLoad {
[super viewDidLoad];
//初始化classView
theView = [[ClassView alloc] initWithFrame:self.view.frame];
theView.backgroundColor = [UIColor lightGrayColor];
self.view = theView;
theView.nameTf.text = self.msg.name;
theView.ageTf.text = self.msg.age;
theView.sexTf.text = self.msg.sex;
if (!self.msg) {
self.title = @"添加数据";
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(save)];
}else{
self.title = @"修改数据";
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(edit)];
}
}
//点击save方法 保存数据
-(void)save{
ClassMessage *message = [[ClassMessage alloc] init];
message.name = theView.nameTf.text;
message.age = theView.ageTf.text;
message.sex =theView.sexTf.text;
//调用数据库方法
[[SqlData initData]initSql];
//调用添加数据方法
[[SqlData initData] addData:message];
//返回上一级
[self.navigationController popViewControllerAnimated:YES];
}
//点击edit方法 修改数据
-(void)edit{
self.msg.name = theView.nameTf.text;
self.msg.age = theView.ageTf.text;
self.msg.sex = theView.sexTf.text;
//调用数据库方法
[[SqlData initData]initSql];
//调用修改数据方法
[[SqlData initData] upData:self.msg];
//返回上一级
[self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end