打开数据库
sqlite3 * db = [Database openDB];
数据库的操作指针 stmt:statement
sqlite3_stmt * stmt = nil;
参数1 , 数据库指针 ,
参数2 SQL语句
参数3 SQL语句的长度 (-1 代表的是无限长 , 自动匹配长度)
参数4 返回数据库操作指针
参数5 为未来做准备的 , 预留参数 , 一般写成NULL
验证SQL语句的正确性
int result = sqlite3_prepare_v2(db, "select * from Student", -1, &stmt, NULL);
NSMutableArray * studentArray = [NSMutableArray array];
判断SQL语句的结果
if (result == SQLITE_OK)
{
while (sqlite3_step(stmt) == SQLITE_ROW) 存在一行数据
{
列数从零开始
int ID = sqlite3_column_int(stmt, 0);
const unsigned char * name = sqlite3_column_text(stmt, 1);
const unsigned char * gender = sqlite3_column_text(stmt, 2);
int age = sqlite3_column_int(stmt, 3);
blob 类型的获取
1. 获取长度
int length = sqlite3_column_bytes(stmt, 4);
2. 获取数据
const void * photo = sqlite3_column_blob(stmt, 4);
3.转换成NSData
NSData * photoData = [NSData dataWithBytes:photo length:length];
4.转成 UIImage
UIImage * image = [UIImage imageWithData:photoData];
封装Student模型
Student * student = [[Student alloc]init];
student.ID = ID;
student.name = [NSString stringWithUTF8String:(const char*)name];
student.age = age;
student.gender = [NSString stringWithUTF8String:(const char *)gender];
student.photo = image;
添加到数组中
[studentArray addObject:student];
}
}
释放stmt指针
sqlite3_finalize(stmt);
关闭数据库
[Database closeDB];
原文地址:http://qccccc.blog.51cto.com/6004423/1555367