将图像存储并检索到iphone的sqlite数据库中

时间:2012-01-04 14:54:13

标签: iphone ios database image sqlite

我试图从sqlite数据库中存储和检索图像和文本。我的saveDatabase编码工作正常..但我不知道它是否保存在我的数据库中..这是我的代码..

    sqlite3 *database;
    dbName=@"dataTable.sqlite";
    NSArray *documentpath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentdir=[documentpath objectAtIndex:0];
    dbPath=[documentdir stringByAppendingPathComponent:dbName];
    sqlite3_stmt *compiledStmt;
   if(sqlite3_open([dbPath UTF8String], &database)==SQLITE_OK){
        NSLog(@"Name:%@,Company:%@,URL:%@",model.personName,model.companyName,model.imgurl);
//        NSString *sqlStatement=[NSString stringWithFormat:@"insert or ignore into Persons(PersonName,CompanyName,ImgUrl)values(\"%@\",\"%@\",\"%@\")",model.personName,model.companyName,model.imgurl];
//           const char *insertSQL=[sqlStatement UTF8String];

       const char *insertSQL="insert or ignore into Persons(PersonName,CompanyName,ImgUrl,UserImage)values(?,?,?,?)";
       sqlite3_bind_text(compiledStmt,1,[model.personName UTF8String],-1,SQLITE_TRANSIENT);
       sqlite3_bind_text(compiledStmt,2,[model.companyName UTF8String],-1,SQLITE_TRANSIENT);
       sqlite3_bind_text(compiledStmt,3,[model.imgurl UTF8String],-1,SQLITE_TRANSIENT);
       NSData *imageData=UIImagePNGRepresentation(imageView.image);
       sqlite3_bind_blob(compiledStmt, 4, [imageData bytes], [imageData length], NULL);
    if(sqlite3_prepare_v2(database,insertSQL, -1, &compiledStmt, NULL)==SQLITE_OK){
        sqlite3_step(compiledStmt);

//    char *errMsg;
//        sqlite3_exec(database, insertSQL, NULL,compiledStmt,&errMsg);
        NSLog(@"Add to Favourites");

当我试图检索我的数据库时,我收到错误..

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSString stringWithUTF8String:]: NULL cString'

这是我阅读数据库的代码..

    sqlite3 *database;

    favArray=[[NSMutableArray alloc]init];
    if(sqlite3_open([dbPath UTF8String],&database)==SQLITE_OK)
    {
        const char *sqlStatement="select * from Persons";
        sqlite3_stmt *compiledStatement;

        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL)==SQLITE_OK)
        {
            while (sqlite3_step(compiledStatement)==SQLITE_ROW) 
            {
                int personId = sqlite3_column_int(compiledStatement,0);

                NSString *personName=[NSString stringWithUTF8String:(char *) sqlite3_column_text(compiledStatement, 1)];

                NSString *companyName=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];

                NSString *imgurl=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
                int length = sqlite3_column_bytes(compiledStatement, 4);
//                NSData *data       = [NSData dataWithBytes:sqlite3_column_blob(compiledStatement, 4) length:length];
                NSString *imageString=[NSString stringWithCharacters:sqlite3_column_blob(compiledStatement, 4) length:length];
                UIImage *personImage=[UIImage imageNamed:imageString];

                Favourites *favourites=[[Favourites alloc]initWithPersonId:personId personName:personName companyName:companyName imgurl:imgurl personImage:personImage];
                [favArray addObject:favourites];
            }
        }sqlite3_finalize(compiledStatement);
    }
    sqlite3_close(database);

我认为我在通过错误的访问数据方式读取数据库时做错了...任何人都帮我从数据库中获取图像......

3 个答案:

答案 0 :(得分:2)

最后我发现哪个地方我有问题...首先我检查数据存储在我的simlator数据库中..没有存储。所以我发现我的插入编码有问题...就是我m在准备声明之前绑定数据...我发现的答案是......

if(sqlite3_prepare_v2(database,insertSQL, -1, &compiledStmt, NULL)==SQLITE_OK){

sqlite3_bind_text(compiledStmt,1,[model.personName UTF8String],-1,SQLITE_TRANSIENT);
       sqlite3_bind_text(compiledStmt,2,[model.companyName UTF8String],-1,SQLITE_TRANSIENT);
       sqlite3_bind_text(compiledStmt,3,[model.imgurl UTF8String],-1,SQLITE_TRANSIENT);
       NSData *imageData=UIImagePNGRepresentation(imageView.image);
       sqlite3_bind_blob(compiledStmt, 4, [imageData bytes], [imageData length], NULL);

sqlite3_step(compiledStmt);

//    char *errMsg;
//        sqlite3_exec(database, insertSQL, NULL,compiledStmt,&errMsg);
        NSLog(@"Add to Favourites");
}

答案 1 :(得分:1)

使用此方法从NSData创建UIImage:

  • (UIImage *)imageWithData:(NSData *)data

答案 2 :(得分:-2)

-(void)btnImage
{
    imgButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [imgButton setImage:[UIImage imageNamed:@"user_default.png"] forState:UIControlStateNormal];
    [imgButton addTarget:self action:@selector(changeImage:) forControlEvents:UIControlEventTouchUpInside];
    imgButton.frame=CGRectMake(100, 50, 120, 120);
    imgButton.layer.cornerRadius=imgButton.frame.size.width/2;
    imgButton.layer.masksToBounds=YES;
    [self.view addSubview:imgButton];
}
-(void)dataBase
{
    NSArray *arr=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[arr objectAtIndex:0];
    simulaterPath=[path stringByAppendingPathComponent:@"imgDataBase.sqlite"];

    NSFileManager *filemanager=[NSFileManager defaultManager];

    if (![filemanager fileExistsAtPath:simulaterPath])
    {
        NSLog(@"hi");
        NSString *xcode=[[NSBundle mainBundle]pathForResource:@"imgDataBase" ofType:@"sqlite"];
        BOOL copy=[filemanager copyItemAtPath:xcode toPath:simulaterPath error:nil];
        if (copy) {
            NSLog(@"copy finish");
            NSLog(@"Simulater:%@",simulaterPath);

        }
    }

}

    imgPicker=[[UIImagePickerController alloc]init];
    imgPicker.allowsEditing=YES;
    imgPicker.delegate=self;
    imgPicker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imgPicker animated:YES completion:nil];

    img=info[UIImagePickerControllerEditedImage];
    path=[info objectForKey:UIImagePickerControllerReferenceURL];
    [imgButton setImage:img forState:UIControlStateNormal];

    urlImage=[NSString stringWithFormat:@"%@",path];
    NSData *data=UIImageJPEGRepresentation(img, 0.8);
    [self SaveImagesToSql:data :urlImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
     ret=[self LoadImagesFromSql:urlImage];
    i=[[UIImage alloc]initWithData:ret];
    [_myImageView setImage:i];
 NSLog( @"\n*****Save image to SQLite*****\n" );
    if (sqlite3_open([simulaterPath UTF8String], &imageDB)==SQLITE_OK) {

    const char* sqliteQuery = "INSERT INTO imgTable (name, imageName) VALUES (?, ?)";
    sqlite3_stmt* statement;

    if( sqlite3_prepare_v2(imageDB, sqliteQuery, -1, &statement, NULL) == SQLITE_OK ) {
        sqlite3_bind_text(statement, 1, [mainUrl UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_blob(statement, 2, [imgData bytes], [imgData length], SQLITE_TRANSIENT);
        sqlite3_step(statement);      
    }
    else NSLog( @"SaveBody: Failed from sqlite3_prepare_v2. Error is:  %s", sqlite3_errmsg(imageDB) );

    // Finalize and close database.
    sqlite3_finalize(statement);
    }

NSData* data = nil;
   // NSString* sqliteQuery = [NSString stringWithFormat:@"SELECT imageName FROM imgTable WHERE name = '%@'", imageLink];
    NSString *sqliteQuery = [NSString stringWithFormat:@"SELECT imageName FROM imgTable"];
    NSString *count=[NSString stringWithFormat:@"SELECT count(imageName) FROM imgTable"];
    sqlite3_stmt* statement;

    if (sqlite3_open([simulaterPath UTF8String], &imageDB)==SQLITE_OK)
    {

        if (sqlite3_prepare_v2(imageDB, [count UTF8String], -1, &statement, NULL)==SQLITE_OK) {

            if( sqlite3_step(statement) == SQLITE_ROW )
            {

                int no=sqlite3_column_int(statement, 0);
                NSLog(@"count=%d",no);
            }

        }

    if( sqlite3_prepare_v2(imageDB, [sqliteQuery UTF8String], -1, &statement, NULL) == SQLITE_OK )
    {

        if( sqlite3_step(statement) == SQLITE_ROW )
        {

            int length = sqlite3_column_bytes(statement, 0);
            data       = [NSData dataWithBytes:sqlite3_column_blob(statement, 0) length:length];
            NSLog(@"%d",i);
        }
    }

    // Finalize and close database.
    sqlite3_finalize(statement);
    }

    return data;