store images into sqlite database - iphone

Below is my code to store images in the sqlite database. When I used it to store values it works and now I'm trying to store images in sqlite database. I don't know what I'm doing wrong. I already searched and I can't get the answer what I need. Anyone help me with his code.
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);
const char *insertSQL="insert into Persons(PersonName,CompanyName,ImgUrl,PersonImage)values(?,?,?,?)";
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);
NSLog(#"Prepare");
sqlite3_step(compiledStmt);
}sqlite3_finalize(compiledStmt);
}
UPDATE:
Thanks to everyone.. I cleared this issue by asked another question from here.. store and retrieve image into sqlite database for iphone This may help to others.

const char *insertSQL="insert into Persons(PersonName,CompanyName,ImgUrl,PersonImage)values(?,?)"
You have 4 values to insert into your table & only 2 placeholders for the parameters. Correct them.
Heck I ain't an iOS developer

you just ADD libSqlite3.dylib to Linked FrameWork and Lilbraries and declared database varibles in .h file
//Database Variables
#property (strong, nonatomic) NSString *databasePath;
#property (nonatomic)sqlite3 *contactDB;
#property (strong, nonatomic) IBOutlet UIButton *backbtn;
#property (strong, nonatomic) IBOutlet UIButton *forwardbtn;
drag and drop UIImageView and name to that... i declared as imgView.
Goto .m file you just copy and paste that code
int i=1;
long long temp=0;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
_databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"images.db"]];
//docsDir NSPathStore2 * #"/Users/gayathiridevi/Library/Application Support/iPhone Simulator/7.0.3/Applications/B5D4D2AF-C613-45F1-B414-829F38344C2A/Documents" 0x0895e160
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: _databasePath ] == NO)
{
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS IMAGETB (ID INTEGER PRIMARY KEY AUTOINCREMENT,URL TEXT, CHECKSUM TEXT,IMAGE BLOB)";
if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog( #"User table Not Created Error: %s", errMsg);
}
else
{
NSLog( #"User table Created: ");
}
sqlite3_close(_contactDB);
}
else {
NSLog( #"DB Not Created");
}
}
[self saveImage];
[self showImage];
}
- (void)saveImage
{
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *insertSQL=#"INSERT INTO IMAGETB(URL,image) VALUES(?,?)";
if(sqlite3_prepare_v2(_contactDB, [insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL)== SQLITE_OK)
{
//NSString *url =#"https://lh6.googleusercontent.com/-vJBBGUtpXxk/AAAAAAAAAAI/AAAAAAAAADQ/nfgVPX1n-Q8/photo.jpg";
//NSString *url =#"http://upload.wikimedia.org/wikipedia/commons/2/2a/Junonia_lemonias_DSF_upper_by_Kadavoor.JPG";
// NSString *url =#"http://upload.wikimedia.org/wikipedia/commons/8/84/Tibia_insulaechorab.jpg";
NSString *url =#"http://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/PNG_transparency_demonstration_2.png/280px-PNG_transparency_demonstration_2.png";
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
NSData *imageData=UIImagePNGRepresentation(image);
sqlite3_bind_text(statement,1, [url UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_blob(statement, 2, [imageData bytes], [imageData length], SQLITE_TRANSIENT);
NSLog(#"Length from internet : %lu", (unsigned long)[imageData length]);
}
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog( #"Insert into row id %lld",(sqlite3_last_insert_rowid(_contactDB)));
temp =(sqlite3_last_insert_rowid(_contactDB));
}
else {
NSLog( #"Error IN INSERT" );
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
}
}
- (void)showImage
{
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if(sqlite3_open(dbpath,&_contactDB)==SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"Select IMAGE FROM IMAGETB WHERE ID = %d",i];
if(sqlite3_prepare_v2(_contactDB,[insertSQL cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL) == SQLITE_OK) {
while(sqlite3_step(statement) == SQLITE_ROW) {
int length = sqlite3_column_bytes(statement, 0);
NSData *imageData = [NSData dataWithBytes:sqlite3_column_blob(statement, 0) length:length];
NSLog(#"Length from db : %lu", (unsigned long)[imageData length]);
if(imageData == nil)
NSLog(#"No image found.");
else
_imgView.image = [UIImage imageWithData:imageData];
NSLog(#"image found.");
}
}
sqlite3_finalize(statement);
}
sqlite3_close(_contactDB);
}
-(IBAction)backBtn:(id)sender {
if (i<=1) {}
else{
i=i-1;
[self showImage];
}
}
-(IBAction)forwardBtn:(id)sender {
if(i==temp){}
else{
i=i+1;
[self showImage];
}
}

I answered a similair question with this answer: It's better if you use CoreData instead. It will be much easier for you to work with CoreDate instead of SQL. CoreData is pretty much an SQL database in a nice wrapper.
If you use iOS 5 you could easily add images to the database without having to worry about them being BLOBS (Binary Large Object) by checking "Allows External Storage".

You should check the return values of bind_text and bind_blob and the step-call, print an error message when they fail.

Related

iOS - using sqlite database update data not working

I would like to update some data in Xcode sqlite db. The db is successfully connected, but seems like there's something wrong in the sql statement, it keeps returning "Failed to add contact", thanks for helping.
- (void) saveData:(id)sender
{
NSLog(#"The code runs through here!");
sqlite3_stmt *statement;
NSString *documents = [self applicationDocumentsDirectory];
NSString *dbPath = [documents stringByAppendingPathComponent:#"monitorDB.sqlite"];
const char *dbpath = [dbPath cStringUsingEncoding:NSASCIIStringEncoding];
if (sqlite3_open(dbpath, & contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:
#"UPDATE profile SET username = \"%#\" WHERE id = 1" ,
self.username.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
self.settingStatus.text = #"Contact added";
} else {
self.settingStatus.text = #"Failed to add contact";
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
} else {
self.settingStatus.text = #"DB Not Connect";
}
}
Try like this..
In viewdidload we need to check wether table exist or not. If not we need to create db.
NSString *docsdir;
NSArray *dirpaths;
dirpaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsdir=[dirpaths objectAtIndex:0];
dabasePath=[NSString stringWithFormat:[docsdir stringByAppendingPathComponent:#"contact.db"]];
NSFileManager *filemgr= [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:dabasePath]==NO ) {
const char *dbpath=[dabasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB)== SQLITE_OK) {
char *error;
const char *sql_stmt="CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, ADDRESS TEXT, NAME TEXT, PHONE TEXT, IMAGE BLOB)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &error)!= SQLITE_OK) {
status.text=#"failed to create";
}
sqlite3_close(contactDB);
}
}
To save data try to use the following code.
-(IBAction)saveData:(id)sender{
sqlite3_stmt *statement;
const char *dbpath = [dabasePath UTF8String];
NSData *imagedata=UIImagePNGRepresentation(imageview.image);
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK) {
NSString *insertSql =[NSString stringWithFormat:#"INSERT INTO CONTACTS (name, address, phone, image) VALUES (\"%#\", \"%#\", \"%#\", ?) ", name.text, address.text, phone.text ];
// NSString *nam=name.text;
const char *insert_stmt = [insertSql UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
sqlite3_bind_blob(statement, 1, [imagedata bytes], [imagedata length], NULL);
if (sqlite3_step(statement) == SQLITE_DONE) {
status.text=#"contact added";
[self clearClick:nil];
}else{
status.text=#"failed to added";
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
}
To update data try to use the following code.
-(IBAction)updateClick:(id)sender{
sqlite3_stmt *updateStmt;
const char *dbpath = [dabasePath UTF8String];
if(sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
const char *sql = "update contacts Set address = ?, phone = ?, image = ? Where name=?";
if(sqlite3_prepare_v2(contactDB, sql, -1, &updateStmt, NULL)==SQLITE_OK){
sqlite3_bind_text(updateStmt, 4, [name.text UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 1, [address.text UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 2, [phone.text UTF8String], -1, SQLITE_TRANSIENT);
NSData *imagedata=UIImagePNGRepresentation(imageview.image);
sqlite3_bind_blob(updateStmt, 3, [imagedata bytes], [imagedata length], NULL);
}
}
char* errmsg;
sqlite3_exec(contactDB, "COMMIT", NULL, NULL, &errmsg);
if(SQLITE_DONE != sqlite3_step(updateStmt)){
NSLog(#"Error while updating. %s", sqlite3_errmsg(contactDB));
}
else{
[self clearClick:nil];
}
sqlite3_finalize(updateStmt);
sqlite3_close(contactDB);
}
Check your sql query and change it like this.
NSString *insertSQL = [NSString stringWithFormat:
#"UPDATE profile SET username = '%#' WHERE id = 1" ,
self.username.text];
Or if you want to do using bind text.
if (sqlite3_open(dbpath, & contactDB) == SQLITE_OK)
{
const char *insert_stmt = "UPDATE profile SET username = ? WHERE id = 1";
if(sqlite3_prepare_v2(contactDB, insert_stmt,
-1, &statement, NULL)== SQLITE_OK)
{
sqlite3_bind_text(statement, 1, [self.username.text UTF8String], -1, SQLITE_TRANSIENT);
}
if (sqlite3_step(statement) == SQLITE_DONE)
{
self.settingStatus.text = #"Contact added";
} else {
self.settingStatus.text = #"Failed to add contact";
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
} else {
self.settingStatus.text = #"DB Not Connect";
}
Just check
in .h file NSString *databaseName;
NSString *databasePath;
and in .m file specify databaseName = #"Db name";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
-(void)save:(id)sender
{
[self checkAndCreateDatabase];
sqlite3 *contactDB;
sqlite3_stmt *updateStmt;
if(sqlite3_open([databasePath UTF8String], &contactDB) == SQLITE_OK)
{
NSString *querySql=[NSString stringWithFormat:
#"UPDATE profile SET username = \"%#\" WHERE id = 1" ,
self.username.text];
const char*sql=[querySql UTF8String];
if(sqlite3_prepare_v2(contactDB,sql, -1, &updateStmt, NULL) == SQLITE_OK)
{
if(SQLITE_DONE != sqlite3_step(updateStmt))
{
NSLog(#"Error while updating. '%s'", sqlite3_errmsg(contactDB));
}
else{
sqlite3_reset(updateStmt);
NSLog(#"Update done successfully!");
}
}
sqlite3_finalize(updateStmt);
}
sqlite3_close(contactDB);
}
-(void) checkAndCreateDatabase{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:databasePath];
if(success) return;
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
There are many possibilities check all of the below:
1) Initialize statement with nil
sqlite3_stmt *statement = nil;
2) Try below
if (sqlite3_prepare_v2(contactDB, insert_stmt,-1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
//Updated
}
}
else
{
NSLog(#"error is %s",sqlite3_errmsg(database));
}
Are you sure the dbPath is not in app bundle? We can't update db in the bundle.
sqlite3_prepare_v2() and sqlite3_step() will return an int.
You can find something you want in sqlite3.h.
Like #define SQLITE_BUSY 5 /* The database file is locked */ ...
And, why not use FMDB? You can find it easy on Github. (Link https://github.com/ccgus/fmdb )

How to insert values using sqlite in iphone

i am trying to insert values.But values are not saved.This is my coding.i alredy created the database using sqlite manager.That database name is "feedback.sqlite". If i run the code no errors will be displayed.But if i entered the data then click the save button the data will not be saved.if i run the code "Failed to open/create database" message will be displayed on the simulator.i cant guess where the error is.please give me an idea.thanks in advance.
Ratingviewcontroller.h
#interface RatingViewController : UIViewController <UITextFieldDelegate> {
sqlite3 *contactDB;
IBOutlet UITextField *Traineeid;
IBOutlet UITextField *Trainername;
IBOutlet UITextField *Traineename;
IBOutlet UITextField *Rating;
IBOutlet UILabel *status;
NSString *dbpath;
}
#property(nonatomic, retain) UITextField *Traineeid;
#property(nonatomic, retain) UITextField *Trainername;
#property(nonatomic, retain) UITextField *Traineename;
#property(nonatomic, retain) UITextField *Rating;
#property(nonatomic, retain) UILabel *status;
- (IBAction)saveData:(id)sender;
- (IBAction)findData:(id)sender;
#end
Ratingviewcontroller.m
#implementation RatingViewController
- (void)viewDidLoad {
// Do any additional setup after loading the view, typically from a nib.
NSString *docsDir;
NSArray *dirPaths;
// get the document directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,
NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
dbpath = [[NSString alloc] initWithString:
[docsDir stringByAppendingPathComponent:#"feedback.sqlite"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:dbpath] == NO) {
const char *db = [dbpath UTF8String];
if (sqlite3_open(db, &contactDB) == SQLITE_OK) {
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS CONTACTS (Traineeid INTEGER "
"PRIMARY KEY AUTOINCREMENT, Trainername TEXT, Traineename "
"TEXT, Rating float)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) !=
SQLITE_OK) {
status.text = #"Failed to create table";
}
sqlite3_close(contactDB);
} else {
status.text = #"Failed to open/create database";
}
}
[super viewDidLoad];
}
- (void)saveData:(id)sender {
sqlite3_stmt *statement;
const char *database = [dbpath UTF8String];
if (sqlite3_open(database, &contactDB) == SQLITE_OK) {
NSString *insertSQL =
[NSString stringWithFormat:
#"INSERT INTO CONTACTS (Trainee id, Trainer name, Trainee "
"name,Rating) VALUES (\"%#\",\"%#\", \"%#\", \"%#\")",
Traineeid, Trainername.text, Trainername.text, Rating.text];
/* NSString *insertSQL = [NSString stringWithFormat:#"insert into
CONTACTS
(Traineeid,Trainername,Traineename,Rating) values
(\"%d\",\"%#\", \"%#\",
\"%f\")",[Traineeid integerValue],
Trainername, Traineename,[Rating
float]];*/
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE) {
status.text = #"Contact added";
Traineeid.text = #"";
Trainername.text = #"";
Traineename.text = #"";
Rating.text = #"";
} else {
status.text = #"Failed to add contact";
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
}
- (void)findContact {
const char *datapath = [dbpath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(datapath, &contactDB) == SQLITE_OK) {
NSString *querySQL = [NSString stringWithFormat:
#"select Trainer name,Trainee name,Rating "
"from CONTACT where Traineeid=\"%#\"",
Traineeid];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) ==
SQLITE_OK) {
if (sqlite3_step(statement) == SQLITE_ROW) {
NSString *trainid = [[NSString alloc] initWithUTF8String:
(const char *)sqlite3_column_text(statement, 0)];
Traineeid.text = trainid;
NSString *trainernme = [[NSString alloc] initWithUTF8String:
(const char *)sqlite3_column_text(statement, 1)];
Trainername.text = trainernme;
NSString *traineenme = [[NSString alloc] initWithUTF8String:
(const char *)sqlite3_column_text(statement, 2)];
Traineename.text = traineenme;
NSString *rat = [[NSString alloc] initWithUTF8String:
(const char *)sqlite3_column_text(statement, 3)];
Rating.text = rat;
status.text = #"Match found";
} else {
status.text = #"Match not found";
Traineeid.text = #"";
Trainername.text = #"";
Traineename.text = #"";
Rating.text = #"";
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
#end
try this code and also you already created the database using sqlite manager.Thats why there is no need to create the insert the values.
- (void)viewDidLoad {
if ([filemgr fileExistsAtPath:dbpath]) {
const char *db = [dbpath UTF8String];
if (sqlite3_open(db, &contactDB) == SQLITE_OK) {
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS CONTACTS (Traineeid INTEGER "
"PRIMARY KEY AUTOINCREMENT, Trainername TEXT, Traineename "
"TEXT, Rating float)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) !=
SQLITE_OK) {
status.text = #"Failed to create table";
}
sqlite3_close(contactDB);
} else {
status.text = #"Failed to open/create database";
}
}
[super viewDidLoad];
}

Inserting Image to sqlite iphone

Hi All I'm New to Xcode I'm trying to insert image from UITableView to database(sqlite3) in ios 5
i tried below code
-(void)addItemCUR
{
if(addStmt == nil) {
const char *sql = "insert into Table(C_Name, C_Image) Values(?,?)";
if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_bind_text(addStmt, 1, [C_Name UTF8String], -1, SQLITE_TRANSIENT);
NSData *ImageData = [[NSData alloc] initWithData:UIImagePNGRepresentation(self.C_Image)];
int returnValue = -1;
if(self.C_Image != nil)
returnValue = sqlite3_bind_blob(addStmt, 3, [ImageData bytes], [ImageData length], NULL);
else
returnValue = sqlite3_bind_blob(addStmt, 4, nil, -1, NULL);
if(SQLITE_DONE != sqlite3_step(addStmt))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
//SQLite provides a method to get the last primary key inserted by using sqlite3_last_insert_rowid
rowid = sqlite3_last_insert_rowid(database);
//Reset the add statement.
sqlite3_reset(addStmt);
}
I'm getting Error like
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString CGImage]: unrecognized selector sent to instance 0xb7c0'
*** First throw call stack:
(0x158f052 0x1720d0a 0x1590ced 0x14f5f00 0x14f5ce2 0xf8b6c 0x5c65 0x3182 0x7030 0x16d71d 0x16d952 0x9f586d 0x1563966 0x1563407 0x14c67c0 0x14c5db4 0x14c5ccb 0x1478879 0x147893e 0xdda9b 0x2ac8 0x2a25)
terminate called throwing an exceptionsharedlibrary apply-load-rules all
(gdb
Please any one help me to get through this thanks in advance.
Try to store the images in local document directory.Then store the image path in sqlite.Following code will help you.
NSData *imageData = UIImagePNGRepresentation(photo);//photo - your image
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *pngFilePath = [NSString stringWithFormat:#"%#/photo.png",documentsDir];
[imageData writeToFile:pngFilePath atomically:YES];
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/photo.png", docDirectory];
sqlite3 *database;
#try
{
NSString *query = [NSString stringWithFormat:#"INSERT INTO Photos(PhotoPath) VALUES('%#')",filePath];
NSString *databasePath;
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:#"GolfElite.sqlite"];
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSLog(#"DB opened...");
sqlite3_exec(database, [query UTF8String], NULL, NULL, NULL);
}
}
#catch (NSException * e)
{
NSLog(#"Exception = %#", e);
}
#finally
{
sqlite3_close(database);
}
NSLog(#"Photos inserted successfully..");
This is an example which include information with image , this code is one Demo code...
- (void) saveAllData {
if(isDirty) {
if(updateStmt == nil) {
const char *sql = "update Coffee Set CoffeeName = ?, Price = ?, CoffeeImage = ? Where CoffeeID = ?";
if(sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating update statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_bind_text(updateStmt, 1, [coffeeName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_double(updateStmt, 2, [price doubleValue]);
NSData *imgData = UIImagePNGRepresentation(self.coffeeImage);
int returnValue = -1;
if(self.coffeeImage != nil)
returnValue = sqlite3_bind_blob(updateStmt, 3, [imgData bytes], [imgData length], NULL);
else
returnValue = sqlite3_bind_blob(updateStmt, 3, nil, -1, NULL);
sqlite3_bind_int(updateStmt, 4, coffeeID);
if(returnValue != SQLITE_OK)
NSLog(#"Not OK!!!");
if(SQLITE_DONE != sqlite3_step(updateStmt))
NSAssert1(0, #"Error while updating. '%s'", sqlite3_errmsg(database));
sqlite3_reset(updateStmt);
isDirty = NO;
}
//Reclaim all memory here.
[coffeeName release];
coffeeName = nil;
[price release];
price = nil;
isDetailViewHydrated = NO;
}
Is there any specific reason to store entire image into database?
I would like to suggest you to store image in an application's Documents/Caches folder and only location including image name will be store into your database as varchar, instead of storing the whole image into database.
So that when next time you need to use image, you just have to follow the paths those have been store for an individual image. Thus, application also doesn't has to bother to redraw images repeatedly and that will improve your application's performance too.
Below is sample code for practice..
- (void)saveImage:(UIImage *)image forPerson:(NSString *)fullName
{
// Make file name first
NSString *filename = [fullName stringByAppendingString:#".png"]; // or .jpg
// Get the path of the app documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// Append the filename and get the full image path
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:filename];
// Now convert the image to PNG/JPEG and write it to the image path
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
// Here you save the savedImagePath to your DB
...
}
To get image back and display...
- (UIImage *)loadImage:(NSString *)filePath
{
return [UIImage imageWithContentsOfFile:filePath];
}

not able to insert record in table in objective c

I made iPad application in which,
I want to insert record into database table, but I am unable to do the same.
here is my code snippet,
-(void) insertRecordIntoTableNamed: (NSString *) symbol{
NSString *sql = [NSString stringWithFormat:#"INSERT INTO recentquotes ('symbol', 'dt_tm') VALUES ('%#',datetime())",symbol];
NSLog(#"sql=%#",sql);
char *err;
if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK)
{
sqlite3_close(db);
NSAssert(0, #"Error updating table.");
}
}
my NSLog shows:
sql=INSERT INTO recentquotes ('symbol', 'dt_tm') VALUES ('PATNI',datetime())
this statement is correct, but i am unable to see VALUES PATNI and datetime() in my database table
here is rest of the code,
NSString *filePahs = Nil;
-(NSString *) filePath {
filePahs=[[NSBundle mainBundle] pathForResource:#"companymaster" ofType:#"sql"];
NSLog(#"path=%#",filePahs);
return filePahs;
}
result of above method is:
path=/Users/krunal/Library/Application Support/iPhone Simulator/5.0/Applications/9FF61238-2D1D-4CB7-8E24-9AC7CE9415BC/iStock kotak.app/companymaster.sql
-(void) openDB {
//---create database---
if (sqlite3_open([[self filePath] UTF8String], &db) != SQLITE_OK )
{
sqlite3_close(db);
NSAssert(0, #"Database failed to open.");
}
}
-(void) getAllRowsFromTableNamed: (NSString *) tableName {
//---retrieve rows---
NSString *qsql = #"SELECT * FROM recentquotes";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2( db, [qsql UTF8String], -1, &statement, nil) ==
SQLITE_OK) {
NSLog(#"b4 while");
while (sqlite3_step(statement) == SQLITE_ROW)
{
char *field1 = (char *) sqlite3_column_text(statement, 0);
NSString *field1Str = [[NSString alloc] initWithUTF8String: field1];
[recentqotarray addObject:field1Str];
[field1Str release];
}
//---deletes the compiled statement from memory---
sqlite3_finalize(statement);
NSLog(#"recentqotarray=%#",recentqotarray);
}
}
edit
i wrote this, and when i checked my log i got like this, "in find data" , i didn't got my sql=...
- (void) finddata
{
NSString *databasePath;
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
NSLog(#"in finddata");
if (sqlite3_open(dbpath, &db) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"SELECT * FROM recentquotes"];
NSLog(#"sql=%#",querySQL);
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(db, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"Inside recent quote table");
char *field1 = (char *) sqlite3_column_text(statement, 0);
NSLog(#"Column name=%s",field1);
NSString *field1Str = [[NSString alloc] initWithUTF8String: field1];
[recentqotarray addObject:field1Str];
NSLog(#"array=%#",recentqotarray);
}
sqlite3_finalize(statement);
}
sqlite3_close(db);
}
}
Thanks In Advance
In your:
NSString *sql = [NSString stringWithFormat:#"INSERT INTO recentquotes ('symbol', 'dt_tm') VALUES ('%#',datetime())",symbol];
Instead of '%#' try using \"%#\" , and check if it inserts into your db.
EDIT:
I've been working on DB a lot lately, and i've been able to successfully insert data in my sqlite, i'll write down what i use check if it helps:
NSArray*dirPath;
NSString*docDir;
dirPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docDir=[dirPath objectAtIndex:0];
databasePath=[docDir stringByAppendingPathComponent:#"example.sqlite"];
BOOL success;
NSFileManager*fm=[NSFileManager defaultManager];
success=[fm fileExistsAtPath:databasePath];
if(success)
{
NSLog(#"Already present");
}
NSString*bundlePath=[[NSBundle mainBundle] pathForResource:#"example" ofType:#"sqlite"];
NSError*error;
success=[fm copyItemAtPath:bundlePath toPath:databasePath error:&error];
if(success)
{
NSLog(#"Created successfully");
}
const char*dbPath=[databasePath UTF8String];
if(sqlite3_open(dbPath, &myDB)==SQLITE_OK)
{
NSString*insertSQL=[NSString stringWithFormat:#"insert into extable (name) values (\"%#\")",[nametextField.text]];
const char*insertStmt=[insertSQL UTF8String];
char *errmsg=nil;
if(sqlite3_exec(myDB, insertStmt, NULL, NULL, &errmsg)==SQLITE_OK)
{
NSLog(#"ADDED!");
}
sqlite3_close(myDB);
}

Searching SQLite3 DB in iPhone from input given in UITextfield

I am fairly new to iOS development. I am trying to build application which searches given search term in sqllite3 DB. I am having trouble with binding parameter to that sql statement.Following is my code to read data from database.
-(void) readPlayersFromDatabase
{
NSString * strTemp=[[NSString alloc]init];
strTemp=#"ben";
sqlite3 *database;
players = [[NSMutableArray alloc] init];
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
char *sqlStatement = "SELECT * FROM Player WHERE LENGTH (lastname)>0 AND LENGTH (firstname)>0 AND ( lastname LIKE '%?%' OR firstname LIKE'%?%' OR Height LIKE '%?%' OR Weight LIKE '%?%') ORDER BY lastname,firstname";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
sqlite3_bind_text(compiledStatement, 1, [strTemp UTF8String],-1, SQLITE_TRANSIENT );
sqlite3_bind_text(compiledStatement, 2, [strTemp UTF8String],-1, SQLITE_TRANSIENT );
sqlite3_bind_text(compiledStatement, 3, [strTemp UTF8String],-1, SQLITE_TRANSIENT );
sqlite3_bind_text(compiledStatement, 4, [strTemp UTF8String],-1, SQLITE_TRANSIENT );
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
NSString *playerId = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *playerName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
Player *temp = [[Player alloc] initWithID:playerId name:playerName];
[players addObject:temp];
[temp release];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
All I am getting at the end is name of player which has ? in their name. Can anyone help me out here. Can you also tell me how can I connect UITextfield input to the strTemp in above code ?
Thanks.
What do you want to do exactly? You can send as a parameter to your readPlayersFromDatabase method to your UITextfield input.
Here is my method to select command: I had a class which is called DBOperations. I hope that helps
+ (int) getUserID{
//check DB
if (![DBOperations checkDB])
{
NSString *msgAlert = #"can not access db file.";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Connection error" message:msgAlert
delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
[alert release];
return 0;
}
[DBOperations open];
int _userID = 1;
const char* sql = " select id from Oyuncu ORDER BY id desc";
if (sqlite3_prepare_v2(database, sql, -1, &hydrate_statement, NULL) != SQLITE_OK) {
NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
if (sqlite3_step(hydrate_statement)==SQLITE_ROW)
{
_userID= sqlite3_column_int(hydrate_statement,0);
NSLog(#"%d",_userID);
}
// Execute the query.
sqlite3_finalize(hydrate_statement);
return _userID;
[DBOperations close];
}
+(BOOL) checkDB {
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"dbOyun.db"];
BOOL success = [fileManager fileExistsAtPath:writableDBPath];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return true;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"dbOyun.db"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
return success;
}
+ (void) open{
//check db validity
NSString *dbPath;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
dbPath = [documentsDirectory stringByAppendingPathComponent:#"dbOyun.db"];
if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) {
sqlite3_close(database);
NSAssert1(0, #"Failed to open database with message '%s'.", sqlite3_errmsg(database));
}
}