今天在进行图片存取的过程中遇到了一些问题,在这里给大家分享一下.
写入图片数据
NSString *sql =@"insert into con(name,phone,picture) values (?,?,?)";
sqlite3_stmt *stmt = NULL;
int flag= sqlite3_prepare(db, sql.UTF8String, -1, &stmt, NULL);
if(flag == SQLITE_OK){
sqlite3_bind_text(stmt, 1, contact.name.UTF8String, -1, NULL);
sqlite3_bind_text(stmt, 2, contact.phonenumber.UTF8String, -1, NULL);
!!!!!!!!!//在进行参数绑定的时候需要指定图片二进制流的字节数以及读取长度
sqlite3_bind_blob(stmt, 3, contact.imageData.bytes, (int)contact.imageData.length, NULL);
if (sqlite3_step(stmt)==SQLITE_DONE) {
NSLog(@"插入成功");
}else
{
NSLog(@"插入十遍");
}
读取图片数据
NSMutableArray *array = [NSMutableArray array];
NSString *sql = @"select *from con";
sqlite3_stmt *stmt = nil;
int result =sqlite3_prepare(db, sql.UTF8String, -1, &stmt, NULL);
if (result == SQLITE_OK) {
sqlite3_bind_text(stmt, 1, sql.UTF8String, -1, NULL);
sqlite3_bind_text(stmt, 2, sql.UTF8String, -1, NULL);
sqlite3_bind_blob(stmt, 3, sql.UTF8String, -1, NULL);
while (sqlite3_step(stmt)==SQLITE_ROW) {
NSString *name = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];
NSString *phone = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 2)];
//在这里不能和其他字段一样直接通过字段的下标去拿到需要通过跟屁虫指针找到对应的字段字节数和长度来获取data数据
int bytes = sqlite3_column_bytes(stmt, 3);
const void *value = sqlite3_column_blob(stmt, 3);
if( value != NULL && bytes != 0 ){
//得到我们需要的图片数据
NSData *data = [NSData dataWithBytes:value length:bytes];
Contact *person =[[Contact alloc]init];
person.name = name;
person.imageData = data;
person.phonenumber = phone;
[array addObject:person];
}
}
}
sqlite3_finalize(stmt);