sqlite3在数据库中插入和读取BLOB数据

发布于 2024-10-03 00:17:29 字数 517 浏览 4 评论 0原文

我需要读取 BLOB 数据并将其写入数据库。这是我的结构表

    #define CREATE_TABLE_USERS_SQL "CREATE TABLE IF NOT EXISTS %@ ( \
UserID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, \
Name VARCHAR(50), \
Image BLOB);"

如何将其插入数据库,然后从中检索?

环境:iPhone SDK 4.1 SQLite3数据库。

此代码失败:

        NSData * buf2 = [[NSData alloc] init];
        sqlite3_column_blob(statement, 5);
        buf2 = sqlite3_column_bytes(statement, 5);
        user.image = [UIImage imageWithData: buf2];

I need to read and write BLOB data to a database. Here is my structure table

    #define CREATE_TABLE_USERS_SQL "CREATE TABLE IF NOT EXISTS %@ ( \
UserID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, \
Name VARCHAR(50), \
Image BLOB);"

How can I insert it into database, and then retrieve from it?

Environment: iPhone SDK 4.1 SQLite3 database.

This code fails:

        NSData * buf2 = [[NSData alloc] init];
        sqlite3_column_blob(statement, 5);
        buf2 = sqlite3_column_bytes(statement, 5);
        user.image = [UIImage imageWithData: buf2];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

∞觅青森が 2024-10-10 00:17:29

谢谢大家!!在您的帮助下,我解决了问题,并希望与像我一样的未来初学者分享结果。)

-(void) addToDB
{
    NSLog(@"\nCreating db");
    NSString *str = @"CREATE TABLE IF NOT EXISTS Images (image1 BLOB);";
    int res = SQLITE_ERROR;


    res = sqlite3_open([@"aa.sql" UTF8String], &database);
    res = sqlite3_exec(database, [str UTF8String], NULL, NULL, NULL);

    sqlite3_stmt *updStmt =nil; 

    const char *sql = "INSERT INTO Images (image1) VALUES (?);";
    res = sqlite3_prepare_v2(database, sql, -1, &updStmt, NULL);

    if(res!= SQLITE_OK)
    {
        NSLog(@"Error while creating update statement:%s", sqlite3_errmsg(database));
    }

    UIImage *img = [UIImage imageNamed: @"flower.png"];
    NSData *imageData = [NSData dataWithData: UIImagePNGRepresentation(img)];

    res = sqlite3_bind_blob(updStmt, 1, [imageData bytes], [imageData length] , SQLITE_TRANSIENT);

    if((res = sqlite3_step(updStmt)) != SQLITE_DONE)
    {
        NSLog(@"Error while updating: %@", sqlite3_errmsg(database));
        sqlite3_reset(updStmt);
    } 

    res = sqlite3_reset(updStmt);
    res = sqlite3_close(database);
}

-(void) readFromDB
{
    NSLog(@"\nReading from db");

    NSString *query = @"SELECT image1 from Images";
    int res = SQLITE_ERROR;
    int len = 0;

    res = sqlite3_open([@"aa.sql" UTF8String], &database);

    sqlite3_stmt *statement;
    res = sqlite3_prepare_v2 (database, [query UTF8String], -1, &statement, nil);

    if (res == SQLITE_OK)
    {
        if (sqlite3_step(statement) == SQLITE_ROW)
        {
            len = sqlite3_column_bytes(statement, 0);
            NSData *imgData = [[NSData alloc] initWithBytes: sqlite3_column_blob(statement, 0) length: len];           


            UIImage *img = [[UIImage alloc] initWithData:imgData];

            self.view1.image = img;

        }
    }
    sqlite3_finalize(statement);

    res = sqlite3_close(database);
}

Thanx all!! With yours help I'v solved problem and want to share results for future beginners like I am.)

-(void) addToDB
{
    NSLog(@"\nCreating db");
    NSString *str = @"CREATE TABLE IF NOT EXISTS Images (image1 BLOB);";
    int res = SQLITE_ERROR;


    res = sqlite3_open([@"aa.sql" UTF8String], &database);
    res = sqlite3_exec(database, [str UTF8String], NULL, NULL, NULL);

    sqlite3_stmt *updStmt =nil; 

    const char *sql = "INSERT INTO Images (image1) VALUES (?);";
    res = sqlite3_prepare_v2(database, sql, -1, &updStmt, NULL);

    if(res!= SQLITE_OK)
    {
        NSLog(@"Error while creating update statement:%s", sqlite3_errmsg(database));
    }

    UIImage *img = [UIImage imageNamed: @"flower.png"];
    NSData *imageData = [NSData dataWithData: UIImagePNGRepresentation(img)];

    res = sqlite3_bind_blob(updStmt, 1, [imageData bytes], [imageData length] , SQLITE_TRANSIENT);

    if((res = sqlite3_step(updStmt)) != SQLITE_DONE)
    {
        NSLog(@"Error while updating: %@", sqlite3_errmsg(database));
        sqlite3_reset(updStmt);
    } 

    res = sqlite3_reset(updStmt);
    res = sqlite3_close(database);
}

-(void) readFromDB
{
    NSLog(@"\nReading from db");

    NSString *query = @"SELECT image1 from Images";
    int res = SQLITE_ERROR;
    int len = 0;

    res = sqlite3_open([@"aa.sql" UTF8String], &database);

    sqlite3_stmt *statement;
    res = sqlite3_prepare_v2 (database, [query UTF8String], -1, &statement, nil);

    if (res == SQLITE_OK)
    {
        if (sqlite3_step(statement) == SQLITE_ROW)
        {
            len = sqlite3_column_bytes(statement, 0);
            NSData *imgData = [[NSData alloc] initWithBytes: sqlite3_column_blob(statement, 0) length: len];           


            UIImage *img = [[UIImage alloc] initWithData:imgData];

            self.view1.image = img;

        }
    }
    sqlite3_finalize(statement);

    res = sqlite3_close(database);
}
冧九 2024-10-10 00:17:29

除了选择客户端或编程接口之外,用法与任何其他字符串字段没有什么不同。


[更新] 我还没有运气为 iPhone 进行开发,但我相信它与任何其他 SELECT 或 INSERT 查询相同。确保对 BLOB 进行编码,并用单撇号 (') 将其括起来,就像字符串一样。

Apart from choosing your client or programming interface, usage does not differ from any other string field.


[Update] I haven't had the luck to develop for the iPhone yet, but I believe it's the same as any other SELECT or INSERT query. Make sure to encode the BLOB and enclose it with single apostrophes (') like strings.

攒眉千度 2024-10-10 00:17:29

为什么不使用 Flying Meat 的 Gus Mueller 等人的 fmdb 呢? http://flyingmeat.com/

https://github.com/ccgus/fmdb

如果您发现 fmdb 有用,请去购买一款 Flying Meat 的优秀应用程序。 VoodooPad 或 Acron。

why not use fmdb by Gus Mueller et al, of Flying Meat? http://flyingmeat.com/

https://github.com/ccgus/fmdb

If you find fmdb useful, go and buy one of the excellents apps of Flying Meat. VoodooPad or Acron.

秋叶绚丽 2024-10-10 00:17:29

//-----插入图像

  - (void)setImage:(UIImage *)theImage
 {

  if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
  {    
    NSString *insertProgrammeSql = @"INSERT INTO imageTable (imageName) VALUES (?)";

sqlite3_stmt *statement;

   if (sqlite3_prepare_v2(myDatabase, [insertProgrammeSql cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL) == SQLITE_OK) {

    NSData *imageData = UIImagePNGRepresentation(theImage);

         sqlite3_bind_blob(statement, 1, [imageData bytes], [imageData length], SQLITE_TRANSIENT);

    sqlite3_step(statement);
}
  sqlite3_close(myDatabase);
//  return YES;    
}   


  }

//--------获取图像

   -(UIImage *)getImage

    {

    UIImage *image = nil;


if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{   

NSString *selectSql = @"SELECT image FROM imageTable";

sqlite3_stmt *statement;
if (sqlite3_prepare_v2(myDatabase, [selectSql UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
    int length = sqlite3_column_bytes(statement, 0);
    NSData *imageData = [NSData dataWithBytes:sqlite3_column_blob(statement, 0 ) length:length];

    image = [UIImage imageWithData:imageData];



  sqlite3_finalize(statement);

  }
     sqlite3_close(myDatabase);
  }
 return image;
 }

//-----insert IMAGE

  - (void)setImage:(UIImage *)theImage
 {

  if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
  {    
    NSString *insertProgrammeSql = @"INSERT INTO imageTable (imageName) VALUES (?)";

sqlite3_stmt *statement;

   if (sqlite3_prepare_v2(myDatabase, [insertProgrammeSql cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL) == SQLITE_OK) {

    NSData *imageData = UIImagePNGRepresentation(theImage);

         sqlite3_bind_blob(statement, 1, [imageData bytes], [imageData length], SQLITE_TRANSIENT);

    sqlite3_step(statement);
}
  sqlite3_close(myDatabase);
//  return YES;    
}   


  }

//--------get image

   -(UIImage *)getImage

    {

    UIImage *image = nil;


if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{   

NSString *selectSql = @"SELECT image FROM imageTable";

sqlite3_stmt *statement;
if (sqlite3_prepare_v2(myDatabase, [selectSql UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
    int length = sqlite3_column_bytes(statement, 0);
    NSData *imageData = [NSData dataWithBytes:sqlite3_column_blob(statement, 0 ) length:length];

    image = [UIImage imageWithData:imageData];



  sqlite3_finalize(statement);

  }
     sqlite3_close(myDatabase);
  }
 return image;
 }
甜是你 2024-10-10 00:17:29

此代码失败:

 NSData * buf2 = [[NSData alloc] init];
   sqlite3_column_blob(语句, 5);
   buf2 = sqlite3_column_bytes(语句, 5);
   user.image = [UIImage imageWithData: buf2];

您正在以正确的顺序调用 SQLite 函数。根据 SQLite 文档:

最安全、最容易记住的策略是调用这些例程
通过以下方式之一:

  • sqlite3_column_text() 后跟 sqlite3_column_bytes()
  • sqlite3_column_blob() 后跟 sqlite3_column_bytes()
  • sqlite3_column_text16() 后跟 sqlite3_column_bytes16()

换句话说,你应该调用sqlite3_column_text(),
sqlite3_column_blob() 或 sqlite3_column_text16() 首先强制
结果转换为所需的格式,然后调用 sqlite3_column_bytes() 或
sqlite3_column_bytes16() 查找结果的大小。请勿混合
调用 sqlite3_column_text() 或 sqlite3_column_blob() 并调用
sqlite3_column_bytes16(),并且不要混合调用
sqlite3_column_text16() 并调用 sqlite3_column_bytes()。

但是,buff2 是一个整数,而不是数据指针。 sqlite3_column_bytes 告诉您 blob 中有多少字节。

This code fails:

   NSData * buf2 = [[NSData alloc] init];
   sqlite3_column_blob(statement, 5);
   buf2 = sqlite3_column_bytes(statement, 5);
   user.image = [UIImage imageWithData: buf2];

You are calling the SQLite functions in the correct order. According to the SQLite docs:

The safest and easiest to remember policy is to invoke these routines
in one of the following ways:

  • sqlite3_column_text() followed by sqlite3_column_bytes()
  • sqlite3_column_blob() followed by sqlite3_column_bytes()
  • sqlite3_column_text16() followed by sqlite3_column_bytes16()

In other words, you should call sqlite3_column_text(),
sqlite3_column_blob(), or sqlite3_column_text16() first to force the
result into the desired format, then invoke sqlite3_column_bytes() or
sqlite3_column_bytes16() to find the size of the result. Do not mix
calls to sqlite3_column_text() or sqlite3_column_blob() with calls to
sqlite3_column_bytes16(), and do not mix calls to
sqlite3_column_text16() with calls to sqlite3_column_bytes().

However, buff2 is an integer, not a data pointer. sqlite3_column_bytes tells you how many bytes are in the blob.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文