图像不存储在 sqlite

Posted

技术标签:

【中文标题】图像不存储在 sqlite【英文标题】:Image not store in sqlite 【发布时间】:2017-04-11 07:43:27 【问题描述】:

我做了一个将图像存储到数据库的演示。目前我没有收到任何错误,但我的图像没有存储在 sqlite 数据库中。 请查看下面的代码并告诉我我的错误在哪里。

DBManager 类

sqlite3 *sqlite3DatabaseObject;
sqlite3_stmt* sqlite3Statement;
-(void)database


    directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    documentsDirectory = [directoryPaths objectAtIndex:0];
    NSString * databasePath = [[NSString alloc]initWithString:[documentsDirectory stringByAppendingPathComponent:@"informationdb.sql"]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:databasePath] == NO) 
        const char *dbPath = [databasePath UTF8String];
        if (sqlite3_open(dbPath, &sqlite3DatabaseObject)== SQLITE_OK) 
            char * errorMessage;
            const char *sqlite3Query = "CREATE TABLE IF NOT EXISTS PICTURES (PHOTO BLOB)";
            if (sqlite3_exec(sqlite3DatabaseObject, sqlite3Query, NULL, NULL, &errorMessage)!= SQLITE_OK) 
                NSLog(@"failed = %@",sqlite3DatabaseObject);
            
            sqlite3_close(sqlite3DatabaseObject);
        else
            NSLog(@"failed to create database");
        
    

- (void) SaveImagesToSql: (NSData*) imgData  

    NSString *databasePath = [[NSBundle mainBundle] pathForResource:@"informationdb" ofType:@"sql"];

    const char* sqlite3Query = "INSERT INTO PICTURES (PHOTO) VALUES (?)";
    int openDatabaseResult = sqlite3_open_v2([databasePath UTF8String], &sqlite3DatabaseObject, SQLITE_OPEN_READWRITE , NULL);
    if (openDatabaseResult == SQLITE_OK) 
        int sqlite3Prepare = sqlite3_prepare_v2(sqlite3DatabaseObject, sqlite3Query, -1, &sqlite3Statement, NULL);
        if( sqlite3Prepare == SQLITE_OK ) 
            sqlite3_bind_blob(sqlite3Statement, 1, [imgData bytes], [imgData length], SQLITE_TRANSIENT);
            sqlite3_step(sqlite3Statement);
        
        else
        
            NSLog(@"Error is: %s", sqlite3_errmsg(sqlite3DatabaseObject));
        
        sqlite3_finalize(sqlite3Statement);

    
    else NSLog( @"Error is:  %s", sqlite3_errmsg(sqlite3DatabaseObject) );
    sqlite3_close(sqlite3DatabaseObject);

ViewController 类

- (void)viewDidLoad 
    [super viewDidLoad];
    DBManager * dbmClass = [[DBManager alloc]init];
    [dbmClass database];

    imgView.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(uploadOrCapture)];
    [singleTap setNumberOfTapsRequired:1];
    [imgView addGestureRecognizer:singleTap];


- (IBAction)btnSave:(id)sender 
    DBManager*dbmClass = [[DBManager alloc]init];
    NSData *imageInData = UIImagePNGRepresentation(imgView.image);
    [dbmClass SaveImagesToSql:imageInData];
    [self dismissViewControllerAnimated:YES completion:nil];

我无法找出问题所在。它成功执行了所有代码,但是当我从设备下载数据库并检查时,没有存储图像数据。

提前致谢。 米希尔。

【问题讨论】:

建议:将图像存储到本地目录,并将目录路径保存到sqlite db中。 你能有任何教程链接吗? 您可以将图片保存在文档目录中,并将图片的路径存储在数据库中。 @MihirOza 当你调用 btnSave 时你得到了图像数据? 是的@ios_DEV 我得到了 【参考方案1】:

只需将此函数替换为我的代码,因为您的数据库路径错误

- (void) SaveImagesToSql: (NSData*) imgData  

    directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    documentsDirectory = [directoryPaths objectAtIndex:0];
    NSString * databasePath = [[NSString alloc]initWithString:[documentsDirectory stringByAppendingPathComponent:@"informationdb.sql"]];

    const char* sqlite3Query = "INSERT INTO PICTURES (PHOTO) VALUES (?)";
    int openDatabaseResult = sqlite3_open_v2([databasePath UTF8String], &sqlite3DatabaseObject, SQLITE_OPEN_READWRITE , NULL);
    if (openDatabaseResult == SQLITE_OK) 
        int sqlite3Prepare = sqlite3_prepare_v2(sqlite3DatabaseObject, sqlite3Query, -1, &sqlite3Statement, NULL);
        if( sqlite3Prepare == SQLITE_OK ) 
            sqlite3_bind_blob(sqlite3Statement, 1, [imgData bytes], [imgData length], SQLITE_TRANSIENT);
            sqlite3_step(sqlite3Statement);
        
        else
        
            NSLog(@"Error is: %s", sqlite3_errmsg(sqlite3DatabaseObject));
        
        sqlite3_finalize(sqlite3Statement);

    
    else NSLog( @"Error is:  %s", sqlite3_errmsg(sqlite3DatabaseObject) );
    sqlite3_close(sqlite3DatabaseObject);

这是数据库截图

不要在你的项目中拖到数据库。如果有任何问题,请告诉我

【讨论】:

【参考方案2】:

这里我如何根据您的使用进行修改。

NSData *imageData = UIImagePNGRepresentation(imgView.image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle: NSDateFormatterShortStyle];
dateFormatter.dateFormat = @"ddMMyyyyhhmmss_SSS_a";
NSString *currentTime = [dateFormatter stringFromDate: [NSDate date]];

NSString *imageName=[NSString stringWithFormat:@"Image_%@",currentTime];

NSString *saveFilePath =[NSString stringWithFormat:@"%@.%@",imageName,@"png"];  //Store saveFilePath string to your database

NSString *localFilePath1 = [documentsDirectory stringByAppendingPathComponent:saveFilePath];

[imageData writeToFile:localFilePath1 atomically:YES];

希望对你有帮助。

【讨论】:

以上是关于图像不存储在 sqlite的主要内容,如果未能解决你的问题,请参考以下文章

SQLiteSQLite objects created in a thread can only be used in that same thread.

加密你的SQLite

iOS SQLite使用

加密你的SQLite

图像不存储在 sqlite

iOS之SQLite使用详解