zoukankan      html  css  js  c++  java
  • ios 向sqlite数据库插入和读取图片数据

    向sqlite数据库插入和读取图片数据 (for ios)
    
    假定数据库中存在表 test_table(name,image), 下面代码将图片文件test.png的二进制数据写到sqlite数据库:
    char *name = "test";
    NSString * nameString = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
    NSString * filePath = [[NSBundle mainBundle] pathForResource:nameString ofType:@"png"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        NSData * imgData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:filePath]);
        const  char * sequel = "insert into test_table(name,image) values(?,?)";
     
        sqlite3_stmt * update;
        if (sqlite3_prepare_v2(database, sequel, -1, &update, NULL) == SQLITE_OK)
        {
            sqlite3_bind_text(update, 1, name, -1, NULL);
            sqlite3_bind_blob(update, 2, [imgData bytes], [imgData length], NULL);
            if( sqlite3_step(update) == SQLITE_DONE)
            {
               NSLog(@"已经写入数据");
            }
            sqlite3_finalize(update);
        }  
    }
    else
    {
        NSLog(@"文件不存在");
    }
    
    下面代码从数据库中读取图片二进制数据,然后显示图片:
    const char * sequel = "select image from test_table where name=?";
    sqlite3_stmt * getimg;
    if (sqlite3_prepare_v2(database, sequel, -1, &getimg, NULL) == SQLITE_OK)
    {
        char *name = "test";
        sqlite3_bind_text(update, 1, name, -1, NULL);
        if(sqlite3_step(getimg)  == SQLITE_ROW)
        {
            int bytes = sqlite3_column_bytes(getimg, 0);
            Byte * value = (Byte*)sqlite3_column_blob(getimg, 1);
            if (bytes !=0 && value != NULL)
            {
                NSData * data = [NSData dataWithBytes:value length:bytes];
                UIImage * img = [UIImage imageWithData:data];
                UIImageView * aview =[[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, IMAGE_WIDTH, IMAGE_HEIGHT)];
                aview.image = img;
                [self.view addSubview:aview];
                [aview release];
             }
         }
         sqlite3_finalize(getimg);
    }

    转:http://blog.csdn.net/moliyll/article/details/7953656

    参考:http://wiki.eoe.cn/page/iOS_blog_page_96451.html

  • 相关阅读:
    Scanner类
    16 String类
    15_面向对象_01
    14_面向对象_01_2 完整格式
    14_面向对象_01_1 成员变量 成员方法
    13_面向对象辅助看懂实例
    面向对象的基本概念
    Servlet_03 进阶随笔 两种域的运用调用方式
    Servlet_03 资源跳转 关键字
    Servlet_02 资源跳转
  • 原文地址:https://www.cnblogs.com/ygm900/p/3470227.html
Copyright © 2011-2022 走看看