Database is locked sqlite ios - objective-c

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

Related

sqlite3_step(statement) == SQLITE_DONE statement not return yes

all time saatment not return no.
-(BOOL)updateProductTable:(NSString *)productid column_shop_Product_quantity:(NSString *) productquantity{
NSLog(#"%#",productid);
NSLog(#"%#",productquantity);
const char *dbpath = [databasepath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *updateSQL = [NSString stringWithFormat:#"UPDATE ShopProduct set column_shop_Product_quantity=%# WHERE column_shop_Product_id=%#",productquantity,productid];
NSLog(#"%#",updateSQL);
const char *update_stmt = [updateSQL UTF8String];
if (sqlite3_prepare_v2(database, update_stmt, -1, &statement, nil) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_DONE)
{
sqlite3_reset(statement);
return YES;
}
else {
return NO;
}
sqlite3_finalize(statement);
}
}
sqlite3_close(database);
return NO;
}
There are several issues with your code:
Never bind values to a query using stringWithFormat:.
You don't close the database in most cases.
You don't finalize the prepared statement in most cases.
You should add more error logging to determine the cause of any issues.
Why is the product quantity passed as a string instead of a number?
You should use sqlite3_open_v2.
Use local variables for the database and prepared statement.
Here is your code updated for all of these issues:
-(BOOL)updateProductTable:(NSString *)productid column_shop_Product_quantity:(NSString *)productquantity {
NSLog(#"%#",productid);
NSLog(#"%#",productquantity);
BOOL res = NO;
sqlite3 *database = NULL;
const char *dbpath = [databasepath UTF8String];
if (sqlite3_open_v2(dbpath, &database, SQLITE_OPEN_READWRITE, NULL) == SQLITE_OK)
{
const char *updateSQL = "UPDATE ShopProduct set column_shop_Product_quantity=? WHERE column_shop_Product_id=?";
sqlite3_stmt *statement = NULL;
if (sqlite3_prepare_v2(database, updateSQL, -1, &statement, NULL) == SQLITE_OK)
{
sqlite3_bind_int(statement, 0, [productquantity intValue]);
sqlite3_bind_text(statement, 1, [productid UTF8String], -1, SQLITE_TRANSIENT);
if (sqlite3_step(statement) == SQLITE_DONE) {
res = YES;
} else {
NSLog(#"Unable to update data: %s", sqlite3_errmsg(database));
}
sqlite3_finalize(statement);
} else {
NSLog(#"Unable to prepare statement: %s", sqlite3_errmsg(database));
}
sqlite3_close(database);
} else {
NSLog(#"Unable to open database at %#: %s", databasepath, sqlite3_errmsg(database));
}
return res;
}

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

How to Compare two rows in Sqlite3 table?

Here i m trying to compare details of rows values in consisting table.here my table contents [here my table
][1]
and also here my code
`-
(IBAction)LogIn:(id)sender {
sqlite3 *dbConnection;
const char *dbpath = [[sharedobj getSandboxPath] UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &dbConnection) == SQLITE_OK)
{
NSString *querySQL = #"SELECT USERNAME, PASSWORD FROM NEWVALUES";
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(dbConnection,
query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *emailId = [[NSString alloc]
initWithUTF8String:
(const char *) sqlite3_column_text(statement,0)];
NSString *password = [[NSString alloc]
initWithUTF8String:(const char *)
sqlite3_column_text(statement, 1)];
if ([emailId isEqualToString:self.userNameField.text] || [password isEqualToString:self.passwordField.text]) {
NSLog(#"Login Credentials Correct");
CHECKViewController *checkobj=[self.storyboard instantiateViewControllerWithIdentifier:#"CHECK"];
[self.navigationController pushViewController:checkobj animated:YES];
}
else{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"Login Credentials are Incorrect"
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:#"OK ", nil];
[alert show];
}
}
NSLog(#"Login Details %# %#",self.userNameField.text ,self.passwordField.text );
}
sqlite3_finalize(statement);
}
else{
NSLog(#"SQLITE NOT OK");
NSLog(#"Error %s ", sqlite3_errmsg(dbConnection));
}
sqlite3_close(dbConnection);
}
imgur.com/QW6KX.png
when enter first row values it working but when i enter second row values it not comparing .what i m doing wrong here?
Please give suggestions to fix this issue.
thanks in advance.

Sqlite3 step == SQLITE_ROW not working for me

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.

SQLite: Update command don't change value

I have this problem.... the code below don't produce errors but the table not commit change!
I've controlled all logs, all value are correct and all If test gone fine, but the value on the db not change.
someone have an idea?
thanks!!
- (void) saveData {
//database file system
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"enduroRace.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"unable to load db: '%#'.", dbPath);
}
//apro database
sqlite3 *db;
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"unable to open DB");
}
//inizio query
sqlite3_stmt *statement;
NSString *querySQL = #"UPDATE setting SET delay=?";
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(db, query_stmt, -1, &statement, NULL) == SQLITE_OK) {
int valoreAttuale = [[sharedClass sharedController] ritardoMusic];
sqlite3_bind_int(statement, 1,valoreAttuale);
}
if (sqlite3_step(statement) != SQLITE_DONE)
{
NSLog(#"Error...");
}
sqlite3_finalize(statement);
sqlite3_close(db);
}
I'm understood.... I've copied the Sqlite db into 'Documents' folder that is not only read only and now is perfect!!! thanks to me !!!