// 数据库存放的目录 NSString *dbPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/test2.db"]; NSLog(@"dbPath : %@",dbPath); // 如果数据库文件不存在,自动创建,否则打开数据库 sqlite3 *database; int ret = sqlite3_open([dbPath UTF8String],&database); if (ret != sqlITE_OK) { NSLog(@"database open Failed!"); return; } // sql语句 NSString *sql = @"CREATE TABLE IF NOT EXISTS history (hid integer primary key autoincrement not null,image blob)"; // 创建会话 sqlite3_stmt *stmt; ret = sqlite3_prepare_v2(database,[sql UTF8String],sql.length,&stmt,NULL); if (ret != sqlITE_OK) { NSLog(@"create statement Failed!"); sqlite3_close(database); return; } // 执行sql语句 ret = sqlite3_step(stmt); if (ret != sqlITE_DONE) { NSLog(@"step Failed!"); // 终止会话 sqlite3_finalize(stmt); sqlite3_close(database); return; } // 插入数据 NSString *insertImage = @"INSERT INTO history (image) VALUES(?)"; ret = sqlite3_prepare_v2(database,[insertImage UTF8String],-1,NULL); if (ret != sqlITE_OK) { NSLog(@"prepare stmt2 Failed"); sqlite3_close(database); return; } // 给会话绑定图片数据 UIImage *image = [UIImage imageNamed:@"login.jpg"]; NSData *imageData = UIImageJPEGRepresentation(image,0.5); sqlite3_bind_blob(stmt,1,[imageData bytes],[imageData length],NULL); ret = sqlite3_step(stmt); if (ret != sqlITE_DONE) { NSLog(@"insert stmt Failed"); sqlite3_finalize(stmt); sqlite3_close(database); return; } // 查询数据 NSString *selectsql = @"SELECT * FROM history"; sqlite3_prepare_v2(database,[selectsql UTF8String],NULL); // 每次只会取一行数据 int result = sqlite3_step(stmt); while (result == sqlITE_ROW) { // 取出图片 const void *image = sqlite3_column_blob(stmt,1); int length = sqlite3_column_bytes(stmt,1); NSData *imageData = [NSData dataWithBytes:image length:length]; // 写出去 [imageData writeToFile:@"/Users/apple/Desktop/shabi.jpg" atomically:YES]; result = sqlite3_step(stmt); } sqlite3_finalize(stmt); sqlite3_close(database);