第三方FMDB的简单使用

时间:2022-06-01 22:06:27

1,导入第三方头文件

#import "FMDB.h"

//定义全局变量

@implementation InputInformationViewController

{

    UITextField *_accountField;//帐号输入框

    UITextField *_passwordsField;//密码输入框

    FMDatabase *db;//数据库

}

 

//获取数据库

            NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask , YES) lastObject];

            NSLog(@"%@",doc);

            NSString *fileName = [doc stringByAppendingPathComponent:@"information.sqlite"];

            //获取数据库

            db = [FMDatabase databaseWithPath:fileName];

            if ([db open]) {

                //创表

                BOOL result = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS M_Information (id integer PRIMARY KEY AUTOINCREMENT, account NOT NULL,passwords text NOT NULL);"];

                if (result) {

                    NSLog(@"创表成功");

                }else{

                    NSLog(@"创表失败");

                }

            }

            

            //获取数据

            NSString *account = _accountField.text;

            NSString *passwords = _passwordsField.text;

            if([db executeUpdate:@"INSERT INTO M_Information(account,passwords) VALUES(?,?);",account,passwords]){

                NSLog(@"111");

            };

            //[db executeQueryWithFormat:@"INSERT INTO M_Information(account,passwords)VALUES(%@,%@);",account,passwords];

            [self query];//执行查询语句

 

//查询语句函数

   ViewController *VC = [[ViewController alloc]init];

    VC.dataArray = [[NSMutableArray alloc]init];

    //执行查询语句

    FMResultSet *resultSet = [db executeQuery:@"SELECT * FROM M_Information"];

   //遍历结果集

    while ([resultSet next]) {

        //传递数据库中的数据

        InformationModel *model = [[InformationModel alloc]init];

        model.myAccount = [resultSet stringForColumn:@"account"];

        model.myPasswords = [resultSet stringForColumn:@"passwords"];

        [VC.dataArray addObject:model];

    }