IOS之Sqlite3的简单实现

来源:互联网 发布:java preparestatement 编辑:程序博客网 时间:2024/06/16 19:43

思路:利用外部工具简单实现数据库的数据调用

工具:mesaSQLite(下面为数据库)



使用:首先安装,安装好后,打开后台,创建一个数据库:ls->cd desktop-> sqlite3 li.db -> create table shujuku(id integer primary key , name text, number integer,sex text);

上面的操作就完成了创建一个文件名为li.db,数据库名为shujuku,各项分别为:编号(id),姓名(name ),号码(number),性别(sex)的数据库




之后就是你要在数据库中创建自己想要的数据

如下图,刚刚选择的时候是空的,首先要按右下角的加号,添加一行,再按右上角的show all按键,就能显示你现有的数据库列表,就像是在excel中添加数据一样,添加自己的数据


 

数据填写好之后,就是如何将数据倒入工程中,用add file的方法将数据库添加到工程中




之后就是在工程中导入相应的文件,包括:




FMDB是第三方的库,libsqlite3.dylib是Xcode自带的框架

导入后,运行一下发现报错,是因为FMDB不支持arc,要手动的利用-fno-objc-arc的方法关掉arc,再运行,就不会有错误了


.h文件中不需要写什么代码,直接在.m中引入数据库,代码如下:

//

//  LYXViewController.m

//  ssdf

//

//  Created by Lee-Yongxing on 13-7-15.

//  Copyright (c) 2013 阿阿. All rights reserved.

//


#import "LYXViewController.h"


#import "FMDatabase.h"


@interface LYXViewController ()


@end


@implementation LYXViewController


- (void)viewDidLoad

{

    [super viewDidLoad];

    //将数据库的数据引入到一个字符串中

    

    NSString * str = [[NSBundle mainBundle]pathForResource:@"li"ofType:@"db"];

    

    //将字符串赋给一个数据库对象

    

    FMDatabase * FMD = [[FMDatabase alloc]initWithPath:str];

    

    //打开数据库,如果没有这个步骤,是看不到数据的

    

    [FMD open];


    //打印数据库,发现再工程中已经有了一个内存地质

    

    NSLog(@"FMD == %@",FMD);

    

    //通过表名将数据库中的数据放到FMResultSet

    

    FMResultSet * resultSet  = [FMD executeQuery:@"select * from shujuku" ];

    

    //遍历数据结果,并将想要的列数据放到每个动态的数组中

    

 

    while ([resultSet next])

    {

        

        NSMutableArray * array = [[NSMutableArray alloc]init];

        

         NSMutableArray * array1 = [[NSMutableArray alloc]init];

        

         NSMutableArray * array2 = [[NSMutableArray alloc]init];

        

         NSMutableArray * array3 = [[NSMutableArray alloc]init];

        

        //id放入动态数组array

        

        [array addObject:[resultSet stringForColumn:@"id"]];

        

        //name放入动态数组array1

        

        [array1 addObject:[resultSet stringForColumn:@"name"]];

        

        //number放入动态数组array2

        

        [array2 addObject:[resultSet stringForColumn:@"number"]];

        

        //sex放入动态数组array3

        

        [array3 addObject:[resultSet stringForColumn:@"sex"]];

        

        //打印各个数组中的数据,可以看到,每一列的数据已经放到了各个动态的数组中

        

        NSLog(@" array ==== %@",array);

        NSLog(@" array1 ==== %@",array1);

        NSLog(@" array2 ==== %@",array2);

        NSLog(@" array3 ==== %@",array3);

       

       

        

    }

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end



原创粉丝点击