NSArray * array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * docPath = [array objectAtIndex:0];
NSString * dbPath = [docPath stringByAppendingPathComponent:@"test_db"];
NSLog(@"dbPath:%@",dbPath);
sqlite3 * database;
if( sqlite3_open([dbPath UTF8String], &database ) == SQLITE_OK)
{
NSLog(@"open success");
}
else
{
NSLog(@"open falied");
}
char * errorMsg;
NSString * sql = @"create table if not exists mytable( myid int not null primary key , age int , name varchar(255))";
if( sqlite3_exec(database, [sql UTF8String], NULL, NULL, &errorMsg) == SQLITE_OK )
{
NSLog(@"create table success");
}
else
{
NSLog(@"create talbe falied:%s",errorMsg);
sqlite3_free(errorMsg);
}
sql = @"insert into mytable(myid , age , name )values(100,18,'rollrock')";
if( sqlite3_exec(database, [sql UTF8String], NULL, NULL, &errorMsg) == SQLITE_OK )
{
NSLog(@"insert success");
}
else
{
NSLog(@"insert falied:%s",errorMsg);
sqlite3_free(errorMsg);
}
sqlite3_stmt * stmt;
sql = @"update mytable set name='rollrock&aaa' where myId = 100";
if( sqlite3_prepare_v2(database, [sql UTF8String], -1,&stmt , NULL ) == SQLITE_OK )
{
//一定要执行这句话才能生效
if( sqlite3_step(stmt) == SQLITE_DONE)
{
NSLog(@"update success");
}
}
else
{
NSLog(@"update false");
}
sql = @"select * from mytable";
if( sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt, nil) == SQLITE_OK )
{
NSLog(@"select success");
//
while( sqlite3_step(stmt) == SQLITE_ROW)
{
int myId = sqlite3_column_int(stmt, 0);
char * name = sqlite3_column_text(stmt, 2);
int age = sqlite3_column_int(stmt, 1);
NSLog(@"myId:%d name:%s age:%d",myId,name,age);
}
}
else
{
NSLog(@"select falied:%s",errorMsg);
sqlite3_free(errorMsg);
}