Sqlite3 step == SQLITE_ROW not working for me - objective-c

As i am new to Xcode so no idea to fix this issue. Please help me out to figure the actual issue.
Database connection is build up, the query is execute, but I always get the message as : Result not found, after execution the query. :(
- (void)viewDidLoad
{
NSString *MyDirectory;
NSArray *DirectoryPaths;
// Get the documents directory
DirectoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
MyDirectory = [DirectoryPaths objectAtIndex:0];
// Build the path to the database file
MyDBPath = [[NSString alloc]initWithString: [MyDirectory stringByAppendingPathComponent:#"mydb.db"]];
//Status.text = MyDBPath;
const char *Database = [MyDBPath UTF8String];
if (sqlite3_open(Database, &MyConnection) == SQLITE_OK)
{
Status.text = #"Build Connection Successfully...!";
}
else
{
Status.text = #"Failed to open database...!";
}
[super viewDidLoad];
}
- (void) Find
{
const char *Database = [MyDBPath UTF8String];
sqlite3_stmt *SQLStatement;
NSString *Query;
if (sqlite3_open(Database, &MyConnection) == SQLITE_OK)
{
Query = [NSString stringWithFormat:#"SELECT EmpName FROM EmpLogin WHERE EmpID=\"%#\"",MyText.text];
if (sqlite3_prepare_v2(MyConnection, [Query UTF8String], 0, &SQLStatement, nil) == SQLITE_OK)
{
while (sqlite3_step(SQLStatement) == SQLITE_ROW)
{
NSString *Name = [[NSString alloc]
initWithUTF8String:(const char *) sqlite3_column_text(SQLStatement, 0)];
TextResult.text = Name;
}
if (TextResult.text.length > 0)
{
Status.text = #"Result found";
}
else
{
NSLog(#"%s", sqlite3_errmsg(MyConnection));
Status.text = #"Result not found";
TextResult.text = #"";
}
sqlite3_finalize(SQLStatement);
}
else
{
//NSString *decode = [[NSString alloc]initWithCString:Query_Stmt encoding:NSUTF8StringEncoding];
//Status.text = decode;
Status.text = #"Query execution Failed...!";
}
sqlite3_close(MyConnection);
}
}
Sqlite3_step(SQLStatement) == SQLITE_ROW __ nor working

Yes i resolved the issue…!!!!
actually i just change the path of the directory to direct to my DB path.
here is my final and working code… anyway thanks #HotLicks,,, #CL. :) :)
This works like a charm … :)
- (void) Find
{
MyDBPath = #"/Users/zaibi/Documents/IOSProjects/mydb.db";
MyDatabase = [MyDBPath UTF8String];
sqlite3_stmt *SQLStatement;
NSString *Query;
//NSString *decode = [[NSString alloc]initWithCString:Database encoding:NSUTF8StringEncoding];
//NSLog(#"%#",decode);
if (sqlite3_open(MyDatabase, &MyConnection) == SQLITE_OK)
{
Query = [NSString stringWithFormat:#"SELECT EmpName FROM EmpLogin WHERE EmpID=\"%#\"",MyText.text];
if (sqlite3_prepare_v2(MyConnection, [Query UTF8String], -1, &SQLStatement, nil) == SQLITE_OK)
{
if (sqlite3_step(SQLStatement) == SQLITE_ROW)
{
NSString *Name = [[NSString alloc]
initWithUTF8String:(const char *) sqlite3_column_text(SQLStatement, 0)];
TextResult.text = Name;
Status.text = #"Result found";
}
else
{
NSLog(#"%s", sqlite3_errmsg(MyConnection));
Status.text = #"Result not found";
TextResult.text = #"";
}
sqlite3_finalize(SQLStatement);
}
else
{
NSLog(#"%s", sqlite3_errmsg(MyConnection));
Status.text = #"Query execution Failed...!";
}
sqlite3_close(MyConnection);
}
}
while this way of accessing the DB is just confusing… :/
NSString *MyDirectory;
NSArray *DirectoryPaths;
// Get the documents directory
DirectoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
MyDirectory = [DirectoryPaths objectAtIndex:0];
// Build the path to the database file
MyDBPath = [[NSString alloc]initWithString: [MyDirectory stringByAppendingPathComponent:#"mydb.db"]];
//Status.text = MyDBPath;

Sometimes it helps to read the documentation:
If the nByte argument is less than zero, then zSql is read up to the
first zero terminator. If nByte is non-negative, then it is the
maximum number of bytes read from zSql.

Related

Working with SQLite in IOS

Hello, I am using following code to implement SQLite Database in Application. Friends have you any other easiest way to implement
this, Which work with all the content of SQLite Database.
// .h File of DBManager
#import <Foundation/Foundation.h>
#import <sqlite3.h>
#interface DBOperation : NSObject
{
}
+(void)OpenDatabase:(NSString*)path; //Open the Database
//+(void)finalizeStatements;//Closing and do the final statement at application exits
+(void)checkCreateDB;
//+(int) getLastInsertId;
+(BOOL) executeSQL:(NSString *)sqlTmp;
+(NSMutableArray*) selectData:(NSString *)sql;
#end
//
// DBOperation.m
// Puzzle
//
// Created by hbmac1 on 9/22/09.
// Copyright 2009 __MyCompanyName__. All rights reserved.
//
#import "DBOperation.h"
static sqlite3 *database = nil;
static int conn;
#implementation DBOperation
+(void)checkCreateDB
{
#try {
NSString *dbPath,*databaseName;
databaseName=#"pointtable.sqlite";
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docDir = [docPaths objectAtIndex:0];
dbPath = [docDir stringByAppendingPathComponent:databaseName];
BOOL success;
NSFileManager *fm = [NSFileManager defaultManager];
success=[fm fileExistsAtPath:dbPath];
if(success)
{
[self OpenDatabase:dbPath];
return;
}
NSString *dbPathFromApp=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fm copyItemAtPath:dbPathFromApp toPath:dbPath error:nil];
[self OpenDatabase:dbPath];
}
#catch (NSException *exception) {
NSLog(#"%#",[exception reason]);
}
}
//Open database
+ (void) OpenDatabase:(NSString*)path
{
#try
{
conn = sqlite3_open([path UTF8String], &database);
if (conn == SQLITE_OK) {
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
#catch (NSException *e) {
NSLog(#"%#",e);
}
}
+(NSMutableArray*) selectData:(NSString *)sql
{
#try
{
if (conn == SQLITE_OK)
{
sqlite3_stmt *stmt = nil;
if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt, NULL) != SQLITE_OK) {
[NSException raise:#"DatabaseException" format:#"Error while creating statement. '%s'", sqlite3_errmsg(database)];
}
NSMutableArray *obj = [[NSMutableArray alloc]init];
int numResultColumns = 0;
while (sqlite3_step(stmt) == SQLITE_ROW) {
numResultColumns = sqlite3_column_count(stmt);
#autoreleasepool {
NSMutableDictionary *tmpObj = [[NSMutableDictionary alloc]init];
for(int i = 0; i < numResultColumns; i++){
if(sqlite3_column_type(stmt, i) == SQLITE_INTEGER){
const char *name = sqlite3_column_name(stmt, i);
NSString *columnName = [[NSString alloc]initWithCString:name encoding:NSUTF8StringEncoding];
[tmpObj setObject:[NSString stringWithFormat:#"%i",sqlite3_column_int(stmt, i)] forKey:columnName];
} else if (sqlite3_column_type(stmt, i) == SQLITE_FLOAT) {
const char *name = sqlite3_column_name(stmt, i);
NSString *columnName = [[NSString alloc]initWithCString:name encoding:NSUTF8StringEncoding];
[tmpObj setObject:[NSString stringWithFormat:#"%f",sqlite3_column_double(stmt, i)] forKey:columnName];
} else if (sqlite3_column_type(stmt, i) == SQLITE_TEXT) {
const char *name = sqlite3_column_name(stmt, i);
NSString *tmpStr = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, i)];
if ( tmpStr == nil) {
tmpStr = #"";
}
NSString *columnName = [[NSString alloc]initWithCString:name encoding:NSUTF8StringEncoding];
[tmpObj setObject:tmpStr forKey:columnName];
} else if (sqlite3_column_type(stmt, i) == SQLITE_BLOB) {
}
else if (sqlite3_column_type(stmt, i) == SQLITE_NULL) {
const char *name = sqlite3_column_name(stmt, i);
NSString *tmpStr = #"";
NSString *columnName = [[NSString alloc]initWithCString:name encoding:NSUTF8StringEncoding];
[tmpObj setObject:tmpStr forKey:columnName];
}
}
[obj addObject:tmpObj];
}
}
return obj;
} else {
return nil;
}
}
#catch (NSException *exception) {
NSLog(#"%#",[exception reason]);
return nil;
}
}
+(BOOL) executeSQL:(NSString *)sqlTmp {
#try {
if(conn == SQLITE_OK) {
const char *sqlStmt = [sqlTmp cStringUsingEncoding:NSUTF8StringEncoding];
sqlite3_stmt *cmp_sqlStmt1;
int returnValue = sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt1, NULL);
returnValue == SQLITE_OK ? NSLog(#"\n Inserted \n") :NSLog(#"\n Not Inserted \n");
sqlite3_step(cmp_sqlStmt1);
sqlite3_finalize(cmp_sqlStmt1);
if (returnValue == SQLITE_OK)
{
return TRUE;
}
}
return FALSE;
}
#catch (NSException *exception) {
NSLog(#"%#",[exception reason]);
return NO;
}
}
#end
Check FMDB, it is very powerful and a lot easier to work with
(void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSString *docsDir; NSArray *dirPaths; dirPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); docsDir=[dirPaths objectAtIndex:0]; databasePath=[[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"eventDb.db"]]; NSFileManager *filemgr=[NSFileManager defaultManager]; const char *dbpath=[databasePath UTF8String]; if(sqlite3_open(dbpath, &eventDb)==SQLITE_OK) { char *errmsg; const char *sql_stmt="CREATE TABLE IF NOT EXISTS EVENT(EVENTID INTEGER PRIMARY KEY AUTOINCREMENT,ENAME TEXT,ETIME TEXT,TIMAGE TEXT)"; if(sqlite3_exec(eventDb,sql_stmt,NULL,NULL,&errmsg)!=SQLITE_OK) { NSLog(#"falied"); } sqlite3_close(eventDb); } else { NSLog(#"failed to open/create database"); }} //insert dirPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); docsDir=[dirPaths objectAtIndex:0]; databasePath=[[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"eventDb.db"]]; sqlite3_stmt *statement; const char *dbpath=[databasePath UTF8String]; if(sqlite3_open(dbpath, &eventDb)==SQLITE_OK) { { { NSString *insertSQL=[NSString stringWithFormat:#" INSERT INTO EVENT(ENAME,ETIME,TIMAGE) VALUES (\"%#\",\"%#\",\"%#\")",_eventLbl.text,time,name]; const char *insert_stmt=[insertSQL UTF8String]; sqlite3_prepare_v2(eventDb,insert_stmt,-1,&statement,NULL); if(sqlite3_step(statement)==SQLITE_DONE) { NSLog(#"added"); } else { NSLog(#"fail to added"); } }}} //select NSString *docsDir; NSArray *dirPaths; dirPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); docsDir=[dirPaths objectAtIndex:0]; databasePath=[[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"eventDb.db"]]; const char *dbpath=[databasePath UTF8String]; sqlite3_stmt *statment; if(sqlite3_open(dbpath,&eventDb)==SQLITE_OK) { NSString *querySQL=[NSString stringWithFormat:#"SELECT ENAME,ETIME,TIMAGE FROM EVENT "]; const char *query_stmt=[querySQL UTF8String]; if(sqlite3_prepare_v2(eventDb,query_stmt,-1,&statment,NULL)==SQLITE_OK) { while(sqlite3_step(statment)==SQLITE_ROW) { NSString ename=[[NSString alloc]initWithUTF8String:(const char)sqlite3_column_text(statment, 0)]; NSString eTIme=[[NSString alloc]initWithUTF8String:(const char)sqlite3_column_text(statment, 1)]; NSString IMAGENAME=[[NSString alloc]initWithUTF8String:(const char)sqlite3_column_text(statment, 2)]; event *g=[[event alloc] init]; g.eventname=ename; g.eventime=eTIme; g.eventImagename=IMAGENAME; [_arr addObject:g] } sqlite3_finalize(statment); } sqlite3_close(eventDb); } //tableview -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [_tool count]; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *myId=#"myID"; UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:myId]; if (cell==nil) { [[NSBundle mainBundle]loadNibNamed:#"royalkitCell" owner:self options:nil]; cell=_toolCell; cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator; } NSString *tname=[_tool objectAtIndex:indexPath.row]; _toolLabel=(UILabel *)[cell viewWithTag:10]; _toolLabel.text=tname; return cell; } Heading

Database is locked sqlite ios

I write a application have use sqlite save data. I add data to table success. But i can't delete content in table. It notify DATABASE IS LOCKED.
My code:
Code Delete in sqlite
//Xoá tài khoản
-(BOOL) delete_Account
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
const char *delete_Statement = "DELETE FROM info";
if(sqlite3_prepare_v2(database, delete_Statement,-1, &statement, NULL)==SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"DELETE Account : %#", #"Ban da xoa thanh cong!");
return YES;
}
else{
NSLog(#"DELETE Account: %# %s",#"Xoa that bai",sqlite3_errmsg(database));
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return NO;
}
Full code
#import "DBManager.h"
static DBManager *sharedInstance = nil;
static sqlite3 *database = nil;
static sqlite3_stmt *statement = nil;
#implementation DBManager
+(DBManager*)getSharedInstance{
if (!sharedInstance) {
sharedInstance = [[super allocWithZone:NULL]init];
[sharedInstance createDB];
}
return sharedInstance;
}
-(BOOL)createDB{
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: #"Sync.db"]];
BOOL isSuccess = YES;
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
char *errMsg;
const char *sql_statement = "CREATE TABLE IF NOT EXISTS info (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, PASS TEXT, TOKEN TEXT, COMPANY TEXT, CUSTOMER TEXT)";
const char*sql_create_contact_db = "CREATE TABLE IF NOT EXISTS contact (ID INTEGER PRIMARY KEY AUTOINCREMENT, FIRST TEXT, LAST TEXT, PHONE TEXT, EMAIL TEXT)";
if (sqlite3_exec(database, sql_statement, NULL, NULL, &errMsg)
!= SQLITE_OK)
{
isSuccess = NO;
NSLog(#"Failed to create table INFO");
}
if (sqlite3_exec(database, sql_create_contact_db, NULL, NULL, &errMsg)
!= SQLITE_OK)
{
isSuccess = NO;
NSLog(#"Failed to create table CONTACT");
}
sqlite3_finalize(statement);
sqlite3_close(database);
return isSuccess;
}
else {
isSuccess = NO;
NSLog(#"Failed to open/create database");
}
}
return isSuccess;
}
-(BOOL) add_Data_Info:(NSString *)username :(NSString *)password :(NSString *)token
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"INSERT INTO info (name, pass, token, company, customer) VALUES (\"%#\",\"%#\",\"%#\",\"%#\",\"%#\")", username, password, token, #"ON", #"OFF"];
const char *insert_Statement = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_Statement,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
return YES;
}
else {
return NO;
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return NO;
}
//Thêm data vào database
-(BOOL) add_Data_Sync:(NSString *)first :(NSString *)last :(NSString *)phone : (NSString*)email
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"INSERT INTO contact (first,last,phone,email) VALUES (\"%#\",\"%#\",\"%#\",\"%#\")", first, last, phone, email];
const char *insert_Statement = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_Statement,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
return YES;
}
else {
return NO;
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return NO;
}
//Cập nhật token
-(BOOL) update_Data_Info:(NSString *)username : (NSString *) token
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *updateSQL = [NSString stringWithFormat:#"UPDATE info Set token = \"%#\"where name = \"\"%#\")", token, username];
const char *update_Statement = [updateSQL UTF8String];
sqlite3_prepare_v2(database, update_Statement,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
return YES;
}
else {
return NO;
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return NO;
}
//Cập nhật token
-(BOOL) update_Sw_Info:(NSString *)username : (NSString *) status
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *updateSQL = [NSString stringWithFormat:#"UPDATE info Set company = \"%#\" where name = \"%#\" ", status, username];
const char *update_Statement = [updateSQL UTF8String];
sqlite3_prepare_v2(database, update_Statement,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
return YES;
}
else {
return NO;
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return NO;
}
//Xoá tài khoản
-(BOOL) delete_Account
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
const char *delete_Statement = "DELETE FROM info";
if(sqlite3_prepare_v2(database, delete_Statement,-1, &statement, NULL)==SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"DELETE Account : %#", #"Ban da xoa thanh cong!");
return YES;
}
else{
NSLog(#"DELETE Account: %# %s",#"Xoa that bai",sqlite3_errmsg(database));
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return NO;
}
-(BOOL)delete_All_Contact
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *deleteSQL = [NSString stringWithFormat:#"DELETE FROM contact"];
const char *delete_Statement = [deleteSQL UTF8String];
sqlite3_prepare_v2(database, delete_Statement,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_ROW)
{
return YES;
}
else {
return NO;
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return NO;
}
- (NSArray*) getInfo
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:
#"SELECT name, token, pass, company, customer FROM info"];
const char *query_stmt = [querySQL UTF8String];
NSMutableArray *resultArray = [[NSMutableArray alloc]init];
if (sqlite3_prepare_v2(database,
query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *name = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 0)];
[resultArray addObject:name];
NSString *token = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 1)];
[resultArray addObject:token];
NSString *pass = [[NSString alloc]initWithUTF8String:
(const char *) sqlite3_column_text(statement, 2)];
[resultArray addObject:pass];
NSString *company = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(statement, 3)];
[resultArray addObject:company];
NSString *customer = [[NSString alloc]initWithUTF8String:
(const char *) sqlite3_column_text(statement, 4)];
[resultArray addObject:customer];
return resultArray;
}
else{
NSLog(#"Not found");
return nil;
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return nil;
}
//Kiểm tra dữ liệu trong database
-(int)checkContact : (NSString *) txtPhone
{
int check = 0;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:
#"SELECT COUNT(*) FROM contact WHERE phone = \"%#\"",txtPhone];
const char *query_stmt = [querySQL UTF8String];
NSMutableArray *resultArray = [[NSMutableArray alloc]init];
if (sqlite3_prepare_v2(database,
query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
check = 1;
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return check;
}
#end

Cannot achieve a successful sqlite query to display in my text view

I'm trying to display a string of text in a text view. According to NSLog the database is found but, I cannot retrieve the data from the table. Could someone point out what is wrong with my query? (I may need this explained in very simple terms. I've been sing objective-c for only a few days.)
- (void)viewDidLoad {
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:#"trivia_game.db"]];
NSLog(#"Full DB path: %#", databasePath);
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
NSLog(#"[SQLITE] DB not found");
} else {
NSLog(#"[SQLITE] trivia_game.db found");
}
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &questionsForGame) == SQLITE_OK)
{
NSLog(#"[SQLITE] db opened");
NSString *querySQL = [NSString stringWithFormat: #"SELECT question, answer0, answer1, answer2, answer3 FROM questions"];
NSLog(#"[SQLITE] string is: %#", querySQL);
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(questionsForGame, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
NSLog(#"[SQLITE] written!");
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *textField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
questHolder.text = textField;
NSLog(#"[SQLITE] string is: %#",textField);
[textField release];
} else {
questHolder.text = #"query not found";
NSLog(#"[SQLITE] Unable to open database!");
}
sqlite3_finalize(statement);
sqlite3_close(questionsForGame);
} else {
NSLog(#"[SQLITE] Screwed up query!");
questHolder.text = #"query not found";
}
}
[filemgr release];
[super viewDidLoad];
}
log:
[Session started at 2012-05-28 12:27:19 -0300.]
2012-05-28 12:27:20.547 ans[9374:207] Full DB path: /Users/admin/Library/Application Support/iPhone Simulator/4.3/Applications/0B4C50FB-5A3F-4371-83D6-1A2AF95B9F66/Documents/trivia_game.db
2012-05-28 12:27:20.549 ans[9374:207] [SQLITE] trivia_game.db found
2012-05-28 12:27:20.550 ans[9374:207] [SQLITE] db opened
2012-05-28 12:27:20.551 ans[9374:207] [SQLITE] string is: SELECT question, answer0, answer1, answer2, answer3 FROM questions
2012-05-28 12:27:20.553 ans[9374:207] [SQLITE] Screwed up query!
I am not familiar with the SQLite library you're using but I would recommend to switch to Core Data. cf. http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/coredata/cdprogrammingguide.html

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.");
}
}

How to insert UIImage as blob using sqlite3_exec in objective-c

I'm trying to cache some images in sqlite as nsdata and I'm having an issue when I attempt to insert the byte array using sqlite3_exec and a raw SQL string (as NSString)
NSData *imgData = UIImagePNGRepresentation(img);
NSString* sql = [NSString stringWithFormat:#"INSERT INTO persistedimg (imgx,idvalx) VALUES (%#,'%#')", imgData, idValue];
rc = sqlite3_exec(db, [sql UTF8String], callbackFunction, (void*)contextObject, &zErrMsg);
But the problem with the above is I'm adding NSData to the sql string directly instead of the bytes.
I wanted to do something like this
... [imgData bytes], [imgData length]
But because I'm not using the typical "_bind_blob" like approach I'm not sure how to do it w/ a raw string
Update
I'm using a wrapper that I'd like to stick w/ and simply write a new method to support image insert / query commands
the below is my entire wrapper class so far
**
#import "SQLiteAccess.h"
#import <sqlite3.h>
#implementation SQLiteAccess
+ (NSString *)pathToDB {
NSString *dbName = #"test123";
NSString *originalDBPath = [[NSBundle mainBundle] pathForResource:dbName ofType:#"db"];
NSString *path = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *appSupportDir = [paths objectAtIndex:0];
NSString *dbNameDir = [NSString stringWithFormat:#"%#/test123", appSupportDir];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDir = NO;
BOOL dirExists = [fileManager fileExistsAtPath:dbNameDir isDirectory:&isDir];
NSString *dbPath = [NSString stringWithFormat:#"%#/%#.db", dbNameDir, dbName];
if(dirExists && isDir) {
BOOL dbExists = [fileManager fileExistsAtPath:dbPath];
if(!dbExists) {
NSError *error = nil;
BOOL success = [fileManager copyItemAtPath:originalDBPath toPath:dbPath error:&error];
if(!success) {
NSLog(#"error = %#", error);
} else {
path = dbPath;
}
} else {
path = dbPath;
}
} else if(!dirExists) {
NSError *error = nil;
BOOL success =[fileManager createDirectoryAtPath:dbNameDir attributes:nil];
if(!success) {
NSLog(#"failed to create dir");
}
success = [fileManager copyItemAtPath:originalDBPath toPath:dbPath error:&error];
if(!success) {
NSLog(#"error = %#", error);
} else {
path = dbPath;
}
}
return path;
}
+ (NSNumber *)executeSQL:(NSString *)sql withCallback:(void *)callbackFunction context:(id)contextObject {
NSString *path = [self pathToDB];
sqlite3 *db = NULL;
int rc = SQLITE_OK;
NSInteger lastRowId = 0;
rc = sqlite3_open([path UTF8String], &db);
if(SQLITE_OK != rc) {
NSLog(#"Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return nil;
} else {
char *zErrMsg = NULL;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
rc = sqlite3_exec(db, [sql UTF8String], callbackFunction, (void*)contextObject, &zErrMsg);
if(SQLITE_OK != rc) {
NSLog(#"Can't run query '%#' error message: %s\n", sql, sqlite3_errmsg(db));
sqlite3_free(zErrMsg);
}
lastRowId = sqlite3_last_insert_rowid(db);
sqlite3_close(db);
[pool release];
}
NSNumber *lastInsertRowId = nil;
if(0 != lastRowId) {
lastInsertRowId = [NSNumber numberWithInteger:lastRowId];
}
return lastInsertRowId;
}
static int singleRowCallback(void *queryValuesVP, int columnCount, char **values, char **columnNames) {
NSMutableDictionary *queryValues = (NSMutableDictionary *)queryValuesVP;
int i;
for(i=0; i<columnCount; i++) {
[queryValues setObject:values[i] ? [NSString stringWithFormat:#"%s",values[i]] : [NSNull null]
forKey:[NSString stringWithFormat:#"%s", columnNames[i]]];
}
return 0;
}
+ (NSString *)selectOneValueSQL:(NSString *)sql {
NSMutableDictionary *queryValues = [NSMutableDictionary dictionary];
[self executeSQL:sql withCallback:singleRowCallback context:queryValues];
NSString *value = nil;
if([queryValues count] == 1) {
value = [[queryValues objectEnumerator] nextObject];
}
return value;
}
+ (NSNumber *)insertWithSQL:(NSString *)sql {
sql = [NSString stringWithFormat:#"BEGIN TRANSACTION; %#; COMMIT TRANSACTION;", sql];
return [self executeSQL:sql withCallback:NULL context:NULL];
}
+ (void)updateWithSQL:(NSString *)sql {
sql = [NSString stringWithFormat:#"BEGIN TRANSACTION; %#; COMMIT TRANSACTION;", sql];
[self executeSQL:sql withCallback:NULL context:nil];
}
#end
**
Any help with this solution would be huge!
I think a large part of the issue you are running into here is that you are trying to simplify the SQLite3 APIs too much. The APIs are not just for executing textual SQL queries; prepared statements and bind parameters exist for a reason. You shouldn't be trying to insert binary data in a string. That's just asking for problems, especially if your binary data has nulls in it.
To insert blobs, you really do need to use sqlite3_bind_blob with sqlite3_prepare_v2. When you bind the blob, you will need to also use [imgData bytes] as the blob data.
Are you perhaps looking for help reconstructing your API to make this sort of thing easier for this particular image caching use case?
Edit
Here's a simple example using bind to insert binary data. Assume there is a table called my_table with 2 columns: name of type VARCHAR and data of type BLOB. Please note that I have not tested or even tried compiling this, so there may be typos or errors.
sqlite3 *database;
// Open a connection to the database given its file path.
if (sqlite3_open("/path/to/sqlite/database.sqlite3", &database) != SQLITE_OK) {
// error handling...
}
// Construct the query and empty prepared statement.
const char *sql = "INSERT INTO `my_table` (`name`, `data`) VALUES (?, ?)";
sqlite3_stmt *statement;
// Prepare the data to bind.
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:#"something"]);
NSString *nameParam = #"Some name";
// Prepare the statement.
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
// Bind the parameters (note that these use a 1-based index, not 0).
sqlite3_bind_text(statement, 1, nameParam);
sqlite3_bind_blob(statement, 2, [imageData bytes], [imageData length], SQLITE_STATIC);
// SQLITE_STATIC tells SQLite that it doesn't have to worry about freeing the binary data.
}
// Execute the statement.
if (sqlite3_step(statement) != SQLITE_DONE) {
// error handling...
}
// Clean up and delete the resources used by the prepared statement.
sqlite3_finalize(statement);
// Now let's try to query! Just select the data column.
const char *selectSql = "SELECT `data` FROM `my_table` WHERE `name` = ?";
sqlite3_stmt *selectStatement;
if (sqlite3_prepare_v2(database, selectSql, -1, &selectStatement, NULL) == SQLITE_OK) {
// Bind the name parameter.
sqlite3_bind_text(selectStatement, 1, nameParam);
}
// Execute the statement and iterate over all the resulting rows.
while (sqlite3_step(selectStatement) == SQLITE_ROW) {
// We got a row back. Let's extract that BLOB.
// Notice the columns have 0-based indices here.
const void *blobBytes = sqlite3_column_blob(selectStatement, 0);
int blobBytesLength = sqlite3_column_bytes(selectStatement, 0); // Count the number of bytes in the BLOB.
NSData *blobData = [NSData dataWithBytes:blobBytes length:blobBytesLength];
NSLog("Here's that data!\n%#", blobData);
}
// Clean up the select statement
sqlite3_finalize(selectStatement);
// Close the connection to the database.
sqlite3_close(database);