NSString *sql1 = [NSString stringWithFormat: @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')", TABLENAME, NAME, AGE, ADDRESS, @"张三", @"23", @"西城区"]; NSString *sql2 = [NSString stringWithFormat: @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')", TABLENAME, NAME, AGE, ADDRESS, @"老六", @"20", @"东城区"]; [self execSql:sql1]; [self execSql:sql2];
运行程序,插入两条数据,用火狐的sqlite工具查看6、查询数据库并打印数据
NSString *sqlQuery = @"SELECT * FROM PERSONINFO"; sqlite3_stmt * statement; if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) { while (sqlite3_step(statement) == SQLITE_ROW) { char *name = (char*)sqlite3_column_text(statement, 1); NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name]; int age = sqlite3_column_int(statement, 2); char *address = (char*)sqlite3_column_text(statement, 3); NSString *nsAddressStr = [[NSString alloc]initWithUTF8String:address]; NSLog(@"name:%@ age:%d address:%@",nsNameStr,age, nsAddressStr); } } sqlite3_close(db);
打印结果:2012-06-29 13:25:32.205 sqlitDemo[3587:f803] name:张三 age:23 address:西城区 2012-06-29 13:25:32.206 sqlitDemo[3587:f803] name:老六 age:20 address:东城区
最后关闭数据库。例子代码:
具体下载目录在 /2012年资料/7月/3日/iOS教程:SQLite的创建数据库,表,插入查看数据