How to write Data into Database using SQlite? - iphone

I had used this code to write enteries into database but it is no refelecting into it...I don't know why?? Please give your suggestions!!Thanks in advance..
NSString* user_Name=txt_UserName.text;
NSString* password=txt_Password.text;
NSString* rePassword=txt_RePassword.text;
if ([password isEqualToString:rePassword]) {
sqlite3 *database;
sqlite3_stmt *compiledQuery;
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "insert into Main values(?,?)";
sqlite3_prepare_v2(database, sqlStatement, -1, &compiledQuery, NULL);
sqlite3_bind_text(compiledQuery, 1, [user_Name UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(compiledQuery, 2, [password UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(compiledQuery))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
sqlite3_finalize(compiledQuery);
sqlite3_close(database);
}

is the path to the database is correct ? You can check the database path by
NSString *documentsDir = [DbCls getPath];
NSString *databasePath = [documentsDir stringByAppendingPathComponent:DBNAME];
+(NSString *) getPath
{
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
return documentsDir;
}

Related

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];
}

sqlite3_prepare_v2 statement is not SQLITE_OK and I don't know why

I have this code in my viewWillAppear method:
sqlite3 *database;
if (sqlite3_open([[self dataFilePath] UTF8String], &database)
!= SQLITE_OK) {
sqlite3_close(database);
NSAssert(0, #"Failed to open database");
}
sqlite3_stmt *statement;
//why is this if statement failing?
if (sqlite3_prepare_v2(database, [sqlStatement UTF8String],
-1, &statement, nil) == SQLITE_OK) {
It passes the first if statement without entering (which is good). The 2nd if statement is the problem.
The sqlStatement is in the form of SELECT * FROM food WHERE foodType = 'fruit'
I don't understand why it's not getting into the if statement. Any help would be appreciated.
The problem ended up not being in the code, but in the way that I exported the sqlite file. It was a series on INSERT statements, not an actual table.
and make changes according to ur requirement...
-(void) readDataFromDatabase
{
chapterAry = [[NSMutableArray alloc] init];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:#"QuotesApp.sqlite"];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
const char *sqlStatement ="select * from MsExcelTutorial";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
while(sqlite3_step(compiledStatement)==SQLITE_ROW)
{
NSNumber *chapterId = [NSNumber numberWithInt:(int)sqlite3_column_int(compiledStatement, 0)];
NSString *chapter = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *link = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *bookmark = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:chapterId,#"chapterId",chapter,#"chapter",link,#"link",bookmark,#"bookmark", nil];
[chapterAry addObject:dic];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
NSString *DBPath = [ClsCommonFunctions GetDatabasePath];
if ([self OpenDBWithPath:DBPath])//Method to open database connection
{
//filesDB is database object
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select fileID,filePath from tblFiles where isUploadPending =1";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(filesDB, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
// u Need to get data from database...
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
sqlite3_close(filesDB);
}
go through it it will work

Update Database Sqlite

I can't update my database: I connect to it and then I use this function but it must execute but no update:
- (BOOL) updatePoint:(NSString *) word {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"master.sqlite"];
sqlite3_stmt *statement;
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
int newPoint = point + 1;
NSString *sql = [NSString stringWithFormat:#"UPDATE %# SET Point='%d' WHERE Parola=?",
dictionaries1[[[word substringWithRange:NSMakeRange(0,1)] intValue]-1],newPoint];
if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL)==SQLITE_OK)
sqlite3_bind_text(statement,1,[word UTF8String] ,-1, SQLITE_TRANSIENT);
sqlite3_step(statement);
sqlite3_finalize(statement);
//sqlite3_reset(statement);
sqlite3_close(database);
return YES;
} else
return NO;
}
What's wrong?
you can look at this, the update code above seems fine but the only problem that might come may be due to database being overwritten or it might not be present at the specified location.
Problem with inserting data into a table
You can replace the insert code with your update statements

SQLite works on device, but not in simulator. sqlite3_prepare_v2 fails

I'm having problems with SQLite on the iPhone simulator. I've reduced it to a simple test app. sqlite3_prepare_v2 fails. But the real device works fine.
I created a database using sqlite3, and added it to my resources. In my code, in viewDidLoad, I call createEditableCopyOfDatabaseIfNeeded (which is a common, widely-used method, seen everywhere). And then I call the following:-
- (void) queryDatabase {
sqlite3 *database;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"myDatabase.sql"];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
NSMutableString *result = [[NSMutableString alloc] init];
const char *sqlStatement = "select * from people";
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
NSString *firstname = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *surname = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
[result appendFormat:#"%# %#\n", firstname, surname];
}
[resultView setText:result];
}
else {
[resultView setText:#"Problem querying database"];
}
sqlite3_finalize(compiledStatement);
[result release];
}
sqlite3_close(database);
}
On the simulator, sqlite3_prepare_v2 doesn't return SQLITE_OK
Can you please tell, what error are you getting?
To find error you can use
if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) != SQLITE_OK) {
NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
Ensure you have deleted the app icon from simulator & clean all targets before build & run. This will probably resolve your issues.
Uninstall app from simulator and reinstall may work.

Prepare insert query on iPhone

This is not working. When I execute this I get one message, EXC_BAD_ACCESS.
-(void) adddata{
NSString *event=#"max";
NSString *venue=#"tvm";
NSString *edate=#"may 6";
NSString *etime=#"10:30";
int admts=5;
NSString *ima=#"TTTTTTTTT";//ticobj.iimg;
sqlite3 *database;
databaseName = #"smbhDB.sql";
sqlite3_stmt *addStatement=nil ;
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
const char *sql ="insert into tickets (admittance, venue, event, date, time, imagedata) Values (?,?,?,?,?,?)";
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
if(sqlite3_prepare_v2(database, sql, -1, &addStatement, NULL) != SQLITE_OK)
NSAssert1(0, #"444 Error while creating add statement. '%s'", sqlite3_errmsg(database));
sqlite3_bind_int(addStatement,1,admts);
printf("\n\n inthe add ticket ");
sqlite3_bind_text(addStatement, 2, [venue UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStatement, 3, [event UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStatement, 4, [edate UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStatement, 5, [etime UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStatement, 6, [ima UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(addStatement))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
sqlite3_reset(addStatement);