iOS开发中使用FMDB来使程序连接SQLite数据库

2020-01-14 16:38:10于海丽

  YYViewController.m文件

复制代码
//
//  YYViewController.m
//  04-FMDB基本使用
//
//  Created by apple on 14-7-27.
//  Copyright (c) 2014年 wendingding. All rights reserved.
//

 

#import "YYViewController.h"
#import "FMDB.h"

@interface YYViewController ()
@property(nonatomic,strong)FMDatabase *db;
@end

@implementation YYViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    //1.获得数据库文件的路径
    NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *fileName=[doc stringByAppendingPathComponent:@"student.sqlite"];
    
    //2.获得数据库
    FMDatabase *db=[FMDatabase databaseWithPath:fileName];
    
    //3.打开数据库
    if ([db open]) {
        //4.创表
        BOOL result=[db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_student (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL);"];
        if (result) {
            NSLog(@"创表成功");
        }else
        {
            NSLog(@"创表失败");
        }
    }
    self.db=db;

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self delete];
    [self insert];
    [self query];
}

//插入数据
-(void)insert
{
    for (int i = 0; i<10; i++) {
        NSString *name = [NSString stringWithFormat:@"jack-%d", arc4random_uniform(100)];
        // executeUpdate : 不确定的参数用?来占位