SQLite3 (iOS) query not executing - objective-c

I'm having some trouble getting this to work.
This is the code I want to execute:
[self openDB];
sqlite3_stmt *statement;
NSString *sql2 = [NSString stringWithFormat:#"INSERT INTO CheckList (CLName, DateAdd, Active, Costum, Percentage, UserId) VALUES ('ola232332332324', '2012-02-03', 1, 1, NULL, 1)"];
if(sqlite3_prepare_v2(db, [sql2 UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
alert1 = [[UIAlertView alloc]
initWithTitle:#"Grats" message:#"The query was executed!" delegate:self cancelButtonTitle:#"Continue" otherButtonTitles: nil];
[alert1 show];
[alert1 release];
}
else {
NSAssert(0, #"Failed to execute");
}
sqlite3_finalize(statement);
And this is the code I use to call the db:
-(NSString *) filePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"prosegur.sqlite"];
}
-(void) openDB {
sqlite3_open([[self filePath] UTF8String], &db);
if (sqlite3_open([[self filePath] UTF8String], &db) != SQLITE_OK){
NSAssert(0, #"Failed to open db");
}
}
Edit: Trying to use the FMDB, here's the code:
FMDatabase *database = [FMDatabase databaseWithPath:#"prosegur.sqlite"];
if([database open]){
NSLog(#"yes");
[database executeUpdate:#"INSERT INTO CheckList (CLName, DateAdd, Active, Costum, UserId) VALUES ('cenas', '2012-02-0', 1, 1, 1)"];}
else
{
NSLog(#"not");
}
Passes by the [database open] verification, but it doesn't execute the query.
EDIT 2: Already did what it was suggested, i'm starting to think that it creates a database and executes the query inside of it, but since it doesn't exist any table, it ignores that fact.
Here's the updated code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [[paths objectAtIndex:0] retain];
NSString *path = [[docsPath stringByAppendingPathComponent:#"prosegur.sqlite"] retain];
FMDatabase *database = [FMDatabase databaseWithPath:path];
[database open];
if([database open])
{
NSLog(#"yes");
[database executeUpdate:#"INSERT INTO CheckList (CLName) VALUES (?)", #"cenas"];
}
else
{
NSLog(#"no");
}
[database close];

Maybe a silly question, but you are aware that sqlite3_prepare_v2 only prepares the statement and does not actually execute it? You also need to call sqlite3_step to actually do the insert,
You could use sqlite3_exec instead, which simply executes a statement without doing the prepare/execute two-step.

I have had a lot of headache while using standart sqlite3 api in iOS development.
Check out FMDB framework. It is very simple to use, and you can find lots of tutorials on the web.
If you do not want that framework, try using NSError for catching an error on query execution.

Sample Example.
+(BOOL)InsertDataInPin:(NSString *)pin
{
NSString *databasePath =Your DatabasePath;
NSString *SQL=#"INSERT INTO pincode Values(?)";
sqlite3_stmt *dataset;
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK ) {
if (sqlite3_prepare_v2(database, [SQL UTF8String], -1, &dataset, NULL) == SQLITE_OK)
{
sqlite3_bind_text(dataset, 1, [pin UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_step(dataset);
}
sqlite3_close(database);
}
}

I found out the answer, if anyone is having troubles like this, check out the following link:
IPhone Development - Failed to use SQLite
Thanks to all of you for the support!

Related

How much data available in table using row count not working

I want to check at the load time of application whether data is available or not in the table so for that I using following code on the viewload of my first file if available then move to other file else retain same but it can't give perfect result mainly row count is not working
NSString *dbPath;
NSString *docsDir;
NSArray *dirPath;
int count=0;
dirPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir=[dirPath objectAtIndex:0];
dbPath=[[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:#"TimerDataBaseMain.db"]];
NSFileManager *fileManager=[NSFileManager defaultManager];
if([fileManager fileExistsAtPath: dbPath] == YES)
{
const char *databsPath=[dbPath UTF8String];
NSLog(#"from created;");
if(sqlite3_open(databsPath,&sqlDatabase) == SQLITE_OK)
{
const char *query="SELECT COUNT(*) FROM PRJDATA";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(sqlDatabase, query, -1, &statement, NULL)==SQLITE_OK) {
while(sqlite3_step(statement)==SQLITE_ROW)
{
count++;
NSLog(#"from count");
}
NSLog(#"from row count");
}
sqlite3_finalize(statement);
}
sqlite3_close(sqlDatabase);
}
if (count>0) {
ListEventCreated *listObject=[[ListEventCreated alloc] initWithNibName:#"ListEventCreated" bundle:[NSBundle mainBundle]];
listObject.title=#"List of event";
NSLog(#"from if condition");
NSLog(#"%i",count);
[self.navigationController pushViewController:listObject animated:YES];
[listObject release];
listObject=nil;
}
I believe , this is WRONG
SELECT COUNT(*) PRJDATA
You should use this
SELECT COUNT(*) FROM PRJDATA

Insert statement not working for second table on same database in sqlite3 iphone

I have 2 tables on same database.
For first table data is inserted successfully using below code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:#"test.sqlite"];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
(sqlite3_exec(database, "BEGIN TRANSACTION", 0, 0, 0))==SQLITE_OK
if ( sqlite3_exec(database, [insertStatement UTF8String], NULL, NULL, &error) == SQLITE_OK)
{
NSLog(#"------- inserted here ----");
}
else
{
NSLog(#"Error: %s", error);
if(sqlite3_exec(database, "COMMIT", 0, 0, 0) ==SQLITE_OK){
NSLog(#"-------data sucessfully inserted ");
}
else {
NSLog(#"-------data insertion failed");
sqlite3_exec(database, "ROLLBACK", 0, 0, 0);
}
(sqlite3_exec(database, "END TRANSACTION", 0, 0, 0));
sqlite3_close(database);
}
else {
NSLog(#"-------sqlite open error ");
}
The data is inserted successfully as I log.
But when I use the same code for inserting into second table, no data is inserted I get log of
NSLog(#"-------data insertion failed")
I am also opening and closing database at each operation and releasing the handle.
I think sqlite is not allowing me to write on database but don't understand why? Since I have closed database with earlier operation.
Does anyone encountered same problem with no data insertion for 2nd table on same database file.
Addt note: there are no syntax errors and if I don't insert on 1st table then insertion is done on 2nd table which is weird.
Try with this code,
-(NSString*) GetDatabasePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) ;
NSString *documentsDirectory = [paths objectAtIndex:0] ;
return [documentsDirectory stringByAppendingPathComponent:#"test.sqlite"] ;
}
-(void)InsertPurchase
{
sqlite3_stmt *statement=nil;
NSString *path = [self GetDatabasePath];
NSString *query;
if(sqlite3_open([path UTF8String],&db) == SQLITE_OK)
{
query = [NSString stringWithFormat: #"Your insert query"];
if(sqlite3_prepare_v2(db, [query UTF8String], -1, &statement, NULL)
== SQLITE_OK)
{
sqlite3_step(statement);
}
sqlite3_finalize(statement);
}
sqlite3_close(db);
}

How do I insert some data into an Sqlite 3 database

Through the following code I am retrieving data from a Db, however I need to insert some data into a Sqlite3 database with this code before select statement. Can any one tell me where I need to put the insert query and how can I execute it.
I am selecting the datas through the following code:
sqlite3* database;
- (void)initializeDatabase
{
list=[[NSMutableArray alloc] init];
BOOL success;
NSFileManager *filemanager=[NSFileManager defaultManager];
NSError *error;
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory= [paths objectAtIndex:0];
NSString *writablePath=[documentsDirectory stringByAppendingPathComponent:#"SymbolTalk.sqlite"];
success=[filemanager fileExistsAtPath:writablePath];
if(!success)
{
NSString *defaultDBPath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"SymbolTalk.sqlite"];
success=[filemanager copyItemAtPath:defaultDBPath toPath:writablePath error:&error];
if(!success)
{
NSAssert1(0,#"Failed to create writable databasefile withw message %#.",[error localizedDescription]);
}
}
//Specify where to get the database from
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory= [paths objectAtIndex:0];
NSString *path=[documentsDirectory stringByAppendingPathComponent:#"SymbolTalk.sqlite"];
//Open the database
//might have to make database as property
if(sqlite3_open([path UTF8String], &dataBase) ==SQLITE_OK)
{
const char *sql="select filename from scenes";
sqlite3_stmt *statement;
if(sqlite3_prepare(dataBase, sql, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
//NSLog(#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]);
[list addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]];
}
}
}
}
sqlite3_stmt *insert_statement = nil;
const char *sql = "INSERT INTO scenes (filename) VALUES(?)";
if (sqlite3_prepare_v2(database, sql, -1, &insert_statement, NULL) != SQLITE_OK) {
NSAssert1(NO, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
sqlite3_bind_text(insert_statement, 1, [newFilename UTF8String], -1, SQLITE_TRANSIENT);
if (sqlite3_step(insert_statement) == SQLITE_DONE) {
// code if all ok
} else {
NSAssert1(NO, #"Error: failed to insert into the database with message '%s'.", sqlite3_errmsg(database));
}
sqlite3_reset(insert_statement);
sqlite3_finalize(insert_statement);

SQLite insert statement does not insert the new data

SQLite insert statement does not insert the new data
i am using this code
- (void) addN: (number *) theN
{
const char *sql = "insert into table (valueN) Values(?)";
sqlite3_stmt *addStmt = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString * docsDir = [paths objectAtIndex:0];
NSString * thePath = [docsDir stringByAppendingPathComponent: #"theDB.sqlite"];
sqlite3_open([thePath UTF8String], &database);
sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL);
sqlite3_bind_int(addStmt, 1, theN.theNumber);
sqlite3_step(addStmt);
sqlite3_finalize(addStmt);
sqlite3_close(database);
}
and the method to insert the record is
- (IBAction) saveN: (id) sender
{
numbers *theNumbers = [[numbers alloc] init];
number *theNumber = [[number alloc] init];
theNumber.theNumber = newN;
[theNumbers addN:theNumber];
[theNumbers release];
[theNumber release];
}
the code is executed but no record is inserted in the DB.
can someone please point me where is the mistake - cause there obviously is a mistake :)
You're not checking the return values of any of the sqlite3 calls. There's a good chance one of them is failing.
this code seems to work:
- (void) addN: (number *) theN
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *thePath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:#"theDB.sqlite"];
BOOL success = [fileManager fileExistsAtPath:thePath];
if (!success)
{
NSLog(#"Failed to find database file '%#'.", thePath);
}
if (!(sqlite3_open([thePath UTF8String], &database) == SQLITE_OK))
{
NSLog(#"An error opening database, normally handle error here.");
}
const char *sql = "insert into table (valueN) Values(?)";
sqlite3_stmt *addStmt = nil;
if (sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
{
NSLog(#"Error, failed to prepare statement, normally handle error here.");
}
sqlite3_bind_int(addStmt, 1, theN.theNumber);
sqlite3_step(addStmt);
if(sqlite3_finalize(addStmt) != SQLITE_OK)
{
NSLog(#"Failed to finalize data statement, normally error handling here.");
}
if (sqlite3_close(database) != SQLITE_OK)
{
NSLog(#"Failed to close database, normally error handling here.");
}
}

NSImage to blob and blob to NSImage (SQLite, NSData)

First of all, I know that I should not use an SQLite database to store image, but I only store favicon of website which are really small.
My problem is that I try to insert those favicon into the database (seems to work), I convert the favicon to NSData with the -tiffrepresentation method of NSimage and then insert it to my database into a blob column:
NSImage *favico = [webview mainFrameIcon];
[appDelegate insertBookmark:[titleField stringValue] url:[urlfield stringValue] data:[favico TIFFRepresentation]]
The SQLite method look like this:
-(void)insertBookmark:(NSString *)title url:(NSString *)url data:(NSData *)data
{
NSData *imagedata = [[NSData alloc]initWithData:data];
sqlite3 *database;
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSString *query = [NSString stringWithFormat:#"INSERT INTO Bookmarks (title, url, image) VALUES ('%#', '%#', '%#')",title, url, data];
const char *querychar = [query UTF8String];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, querychar, -1, &statement, NULL) == SQLITE_OK)
{
int row = 3;
sqlite3_bind_blob(statement, row, [imagedata bytes], [imagedata length], NULL);
sqlite3_step(statement);
sqlite3_finalize(statement);
}
else
{
NSLog(#"Error");
}
[databasePath retain];
[databaseName retain];
}
sqlite3_close(database);
[imagedata release];
}
When I look into the database I have value in the image column between <data> (normal ? )
Now when I extract the blob from the database and try to put it in my object I got null in the NSimage:
-(void) readDatabase {
// Setup the database object
sqlite3 *database;
bookmarks = [[NSMutableArray alloc] init];
// 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 = "SELECT * FROM Bookmarks ORDER BY title ASC";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aTitle = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aUrl = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(compiledStatement, 3) length:sqlite3_column_bytes(compiledStatement, 3)];
NSImage *image = [[NSImage alloc]initWithData:data];
bookmarkObject *bookmark = [[bookmarkObject alloc] initWithName:aTitle url:aUrl favico:image];
[bookmarks addObject:bookmark];
[bookmark release];
[data release];
[image release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
sqlite3_close(database);
[databasePath retain];
[databaseName retain];
}
}
Thanks in advance
The < and > around your actual data come from NSData. By using %# in your format string and providing data, NSString sends description to data. [NSData description] wraps the content between < and >.
Another issue with your code is, that you seem to mix parameter-less & parameter prepared statements:
Either use stringWithFormat: to create a complete query statement
or use a query like INSERT INTO Bookmarks (title ...) VALUES (? ...) combined with sqlite3_bind_blob
The parameter syntax SQLite supports can be found here:
http://www.sqlite.org/c3ref/bind_blob.html