SQLlite3

来源:互联网 发布:svm分类器 python实现 编辑:程序博客网 时间:2024/05/02 16:54



//执行SQL语句

-(void)execSql:(NSString *)sql

{

    char *error=NULL;

    if(sqlite3_exec(db,[sql UTF8String],NULL,NULL,&error)==SQLITE_OK)

    {

        NSLog(@"创建表成功");

        

    }

    else

        

    {

        NSLog(@"错误%@",[NSString stringWithUTF8String:error]);

    }

    

}

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.


    //设置数据库路径

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

    NSString *dbFileName=[documentpath stringByAppendingPathComponent:@"db.sqlite"];

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

    //打开数据库

    if (sqlite3_open([dbFileName UTF8String], &db)==SQLITE_OK) {

        NSLog(@"打开数据库成功");

    }

    else

    {

        NSLog(@"打开数据库失败!");

    }

    NSString *createTableSql=@"create table user(id integer primary key autoincrement,name text,password text)";

    [self execSql:createTableSql];

    //插入数据

    for (int i=0; i<5; i++) {

        NSString *insertSql=[NSString stringWithFormat:@"insert into user (name,password) values('user%d','%06d')",i+1,arc4random_uniform(100000)];

        [self execSql:insertSql];

    }

    //查询数据

    sqlite3_stmt *state;

    sqlite3_prepare_v2(db, "select * from user", -1, &state, NULL);

    //从结果集中取数据

    while (sqlite3_step(state)==SQLITE_ROW) {

        int ID=sqlite3_column_int(state, 0);

       char *name= (char *)sqlite3_column_text(state, 1);

        char *pwd=(char *)sqlite3_column_text(state, 2);

        NSLog(@"ID=%d,name=%s,pwd=%s",ID,name,pwd);

        NSLog(@"******");

    }

}


0 0
原创粉丝点击