今日的勤奋,只是为了明日拥有可以懒惰的权利!
+ (NSArray *)studentsWithCondition:(NSString *)condition
{
// 0.定义数组
NSMutableArray *students = nil;
// 1.定义sql语句
const char *sql = "select id, name, age from t_student where name like ?;";
// 2.定义一个stmt存放结果集
sqlite3_stmt *stmt = NULL;
// 3.检测SQL语句的合法性
int result = sqlite3_prepare_v2(_db, sql, -1, &stmt, NULL);
if (result == SQLITE_OK) {
NSLog(@"查询语句是合法的");
students = [NSMutableArray array];
// 填补占位符的内容
NSString *newCondition = [NSString stringWithFormat:@"%%%@%%", condition];
// NSLog(@"%@", newCondition);
sqlite3_bind_text(stmt, 1, newCondition.UTF8String, -1, NULL);
// 4.执行SQL语句,从结果集中取出数据
while (sqlite3_step(stmt) == SQLITE_ROW) { // 真的查询到一行数据
// 获得这行对应的数据
IWStudent *student = [[IWStudent alloc] init];
// 获得第0列的id
student.ID = sqlite3_column_int(stmt, 0);
// 获得第1列的name
const unsigned char *sname = sqlite3_column_text(stmt, 1);
student.name = [NSString stringWithUTF8String:(const char *)sname];
// 获得第2列的age
student.age = sqlite3_column_int(stmt, 2);
// 添加到数组
[students addObject:student];
}
} else {
NSLog(@"查询语句非合法");
}
return students;
}
网友评论