#import "ViewController.h" #import <sqlite3.h> #import "Person.h" @interface ViewController () { sqlite3 *_db; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/person.db"]; NSLog(@"%@",path); if(SQLITE_OK!=sqlite3_open(path.UTF8String, &_db))//打开数据库 不存在则创建 { NSLog(@"打开或创建数据库失败!"); return; } char *error; if(SQLITE_OK!=sqlite3_exec(_db, "create table if not exists ‘t_person‘ (name text,age integer,sex text)", nil, nil, &error)) { NSLog(@"创建表失败"); return; } //添加数据 修改删除同理 // for (int i=1; i<=50; i++) { // const char *c=[[NSString stringWithFormat:@"insert into t_person values(‘%@‘,%d,‘%@‘)",[NSString stringWithFormat:@"li%d",i],i,i%[email protected]"男":@"女"] UTF8String]; // if(SQLITE_OK!=sqlite3_exec(_db, c, nil, nil, &error)) // { // NSLog(@"添加数据失败! error:%s",error); // return; // } // } //查询 sqlite3_stmt *stmt; if(SQLITE_OK ==sqlite3_prepare(_db, [@"select * from t_person" UTF8String], -1/*要查询的字节数 -1表示无限制*/, &stmt, nil/*如果限制字节 该参数返回未被查询的数据)) { while(SQLITE_ROW == sqlite3_step(stmt)) { Person *p=[[Person alloc]init]; p.name=[NSString stringWithUTF8String:(const char*)sqlite3_column_text(stmt, 0)]; p.age=sqlite3_column_int(stmt, 1); p.sex=[NSString stringWithUTF8String:(const char*) sqlite3_column_text(stmt, 2)]; NSLog(@"%@--%d--%@",p.name,p.age,p.sex); } } } @end
时间: 2024-11-11 19:39:33