3
- (void)viewDidLoad {
[super viewDidLoad];
[self createDB];
}
-(void)createDB {
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docdir = [path objectAtIndex:0]; //path[0];
dbpath = [docdir stringByAppendingPathComponent:@"arun.sqlite"];
NSLog(@"database path : %@",dbpath);
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:dbpath] == NO) {
//OPEN AND CREATE DATABASE
if (sqlite3_open([dbpath UTF8String], &myDB) == SQLITE_OK) {
//CREATE TABLE
NSString *createSQL = @"CREATE TABLE IF NOT EXISTS STUDENT (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, ROLLNO INTEGER,IMAGE BLOB)";
char *error = nil;
if (sqlite3_exec(myDB, [createSQL UTF8String] , NULL, NULL, &error) == SQLITE_OK) {
NSLog(@"Database and tables created.");
} else {
NSLog(@"Error %s",error);
}
sqlite3_close(myDB);
}
}
}
- (void)saveImage {
sqlite3_stmt *compiledStmt;
sqlite3 *db;
if(sqlite3_open([dbpath UTF8String], &db)==SQLITE_OK) {
NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO STUDENT (ROLLNO,IMAGE) VALUES(\"%@\", \"%@\")", rollnoTxt.text, selectImgvw.image];
if(sqlite3_prepare_v2(db,[insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &compiledStmt, NULL) == SQLITE_OK){
UIImage *image = selectImgvw.image;
NSData *imgdata = UIImagePNGRepresentation(image);
sqlite3_bind_blob(compiledStmt, 1, [imgdata bytes], (int)[imgdata length], SQLITE_TRANSIENT);
if(sqlite3_step(compiledStmt) != SQLITE_DONE) {
NSLog(@"Error: %s", sqlite3_errmsg(db));
} else {
NSLog(@"Insert into row id = %lld", (sqlite3_last_insert_rowid(db)));
}
sqlite3_finalize(compiledStmt);
}
}
sqlite3_close(db);
}
- (void)showImage {
sqlite3_stmt *compiledStmt;
sqlite3 *db;
if(sqlite3_open([dbpath UTF8String], &db)==SQLITE_OK){
NSString *insertSQL = [NSString stringWithFormat:@"SELECT IMAGE FROM STUDENT WHERE ROLLNO = %@",rollnoTxt.text];
if(sqlite3_prepare_v2(db,[insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &compiledStmt, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStmt) == SQLITE_ROW) {
int length = sqlite3_column_bytes(compiledStmt, 0);
NSData *imgdata = [NSData dataWithBytes:sqlite3_column_blob(compiledStmt, 0) length:length];
NSLog(@"Length : %ld", [imgdata length]);
if(imgdata == nil)
NSLog(@"No image found.");
else {
UIImage *img = [UIImage imageWithData:imgdata];
displayImgvw.image = img;
}
}
}
sqlite3_finalize(compiledStmt);
}
sqlite3_close(db);
}
以上是我的代碼片段。 圖像被保存到SQLiteDataBase
但問題是,當獲取圖像時,我沒有得到任何價值時飼料圖像視圖。 我一直在做一段時間。有更多的研究,但無法解決它。 如果有人能解決這個問題,請給我建議。從iOS的SQLite數據庫中存儲和檢索圖像