0

我创建了一个 sqlite 数据库。

我在我的数据库中插入了一些数据..

UIImage * imagee=[UIImage imageNamed:@"image.png"];
NSData *mydata=[NSData dataWithData:UIImagePNGRepresentation(imagee)];
const char *dbpath = [databasePath UTF8String];

NSString *insertSQL=[NSString stringWithFormat:@"insert into CONTACTS values(\"%@\",\"%@\")",@"Mathan",mydata];

NSLog(@"mydata %@",mydata);

sqlite3_stmt *addStatement;

const char *insert_stmt=[insertSQL UTF8String];
if (sqlite3_open(dbpath,&contactDB)==SQLITE_OK) {
    sqlite3_prepare_v2(contactDB,insert_stmt,-1,&addStatement,NULL);

    if (sqlite3_step(addStatement)==SQLITE_DONE) {

        sqlite3_bind_blob(addStatement,1, [mydata bytes], [mydata length], SQLITE_TRANSIENT);
        NSLog(@"Data saved");

    }
    else{

        NSLog(@"Some Error occured");
    }

    sqlite3_close(contactDB);
}
else{
    NSLog(@"Failure");
}

已经编写了一些代码来检索数据

sqlite3_stmt *statement;
if (sqlite3_open([databasePath UTF8String], &contactDB) == SQLITE_OK) {
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM contacts"];

    if (sqlite3_prepare_v2( contactDB, [sql UTF8String], -1, &statement, nil) == SQLITE_OK) {
        while (sqlite3_step(statement) == SQLITE_ROW)
        {
            char *field1 = (char *) sqlite3_column_text(statement, 0);
            NSString *field1Str = [[NSString alloc] initWithUTF8String: field1];
            NSLog(@"UserName %@",field1Str);

            NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(statement, 1) length:sqlite3_column_bytes(statement, 1)];

            UIImage *newImage = [[UIImage alloc]initWithData:data];

            NSLog(@"Image OBJ %@",newImage);
            NSLog(@"Image Data  %@",data);
        }
        sqlite3_close(contactDB);
    }
}

sqlite3_finalize(statement);

问题是

在日志中,插入的NSData对象和检索NSData的对象是不同的(在日志中打印会给出不同的流)

此外,图像 OBJ 在日志中打印为 null ..

在stackoverflow中看到过类似的问题。但似乎没有任何帮助。

4

3 回答 3

0

When you do this:

NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(statement, 1) length:sqlite3_column_bytes(statement, 1)];
UIImage *newImage = [[UIImage alloc]initWithData:data];

You are telling the compiler that the two objects are different, so when you print them, they will always be different. Guaranteed. Since they aren't the same object.

I'm not sure why newImage would display null though since you just allocated the object.

于 2012-10-05T15:20:59.417 回答
0

你应该在sqlite3_step 之后 sqlite3_bind_blob执行,而不是之前。你在告诉它要插入什么之前插入!

检查和的结果也是sqlite_prepare_v2谨慎sqlite3_bind_blob的。

我还建议(与您的问题无关)sqlite3_finalize在您之前sqlite3_close的两个代码片段中。如果你有一个错误,sqlite3_errmsg是一个救命稻草,准确地告诉你出了什么问题,而不是猜测。

于 2012-10-05T15:29:26.057 回答
0

没有重大区别,但您可以尝试使用此方法,也可以在控制台中获取图像长度以检测图像是否从数据库正确响应:

const void *ptr = sqlite3_column_blob(stmt, 1);
int size = sqlite3_column_bytes(stmt, 1);
NSLog(@"%d",size);
data = [[NSData alloc] initWithBytes:ptr length:size];
于 2012-10-05T15:39:18.833 回答