how to insert values in sqlite - iphone

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath =[documentsDir stringByAppendingPathComponent:#"register.sqlite"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
sqlite3_stmt *selectstmt;
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"register.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
sql = "select lastname,email,firstname from reg_FORM";
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
lastname = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
email=[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
firstname=[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
NSLog(#"----%#",lastname);
NSLog(#"----%#",email);
NSLog(#"----%#",firstname);
}
sqlite3_finalize(selectstmt);
}
sqlite3_close(database);
}
I am using this code to retrieve the values in db, but I did know how to insert data in db. I am trying this below code but it does not work
const char *sql = "insert into reg_FORM (firstname,lastname,email,company,phone) VALUES (aaa,aaa,aaa,aaaa,1223)";
sqlite3_exec(database, [[NSString stringWithFormat:#"insert into reg_FORM (firstname,lastname,email,company,phone) VALUES (aaa,aaa,aaa,aaaa,1223)"] UTF8String], NULL, NULL, NULL);
//give code for insert values in db

{
BOOL returnValue = YES;
sqlite3_stmt *insertStmt = nil;
sqlite3 *UserDB ;
if (sqlite3_config(SQLITE_CONFIG_SERIALIZED) == SQLITE_OK)
{
NSLog(#"Can now use sqlite on multiple threads, using the same connection");
}
int ret = sqlite3_enable_shared_cache(1);
if(ret != SQLITE_OK)
{
}
// Open the database. The database was prepared outside the application.
if (sqlite3_open([app.dataBasePath UTF8String], &UserDB) == SQLITE_OK)
{
if(insertStmt == nil)
{
NSString *strValue = [NSString stringWithFormat:#"insert into languagemaster Values(?,?)"];
const char *sql = [strValue UTF8String];
if(sqlite3_prepare_v2(UserDB, sql, -1, &insertStmt, NULL) != SQLITE_OK)
{
NSLog(#"Error while creating insertStmt in tblUserAccount %#", [NSString stringWithUTF8String:(char *)sqlite3_errmsg(UserDB)]);
returnValue = NO;
}
}
if(sqlite3_bind_int(insertStmt, 1, langid) ) // langid is int
{
return NO;
}
if(sqlite3_bind_text(insertStmt, 2, [strLanguageName UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK) // strLanguageName is string
{
return NO;
}
if(SQLITE_DONE != sqlite3_step(insertStmt))
{
NSLog(#"Error while Executing insertStmt in tblLocation %#", [NSString stringWithUTF8String:(char *)sqlite3_errmsg(UserDB)]);
returnValue = NO;
}
sqlite3_reset(insertStmt);
if (insertStmt)
{
sqlite3_finalize(insertStmt);
insertStmt = nil;
}
}
sqlite3_close(UserDB);
return returnValue;
}

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath =[documentsDir stringByAppendingPathComponent:#"register.sqlite"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
sqlite3_stmt *selectstmt;
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"register.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql = "insert into reg_FORM (firstname,lastname,email,company,phone) VALUES ('sdcbb','bbbb','bbbb','bbbb',1111122)";
sqlite3_prepare_v2(database,sql, -1, &selectstmt, NULL);
if(sqlite3_step(selectstmt)==SQLITE_DONE)
{
NSLog(#"insert successfully");
}
else
{
NSLog(#"insert not successfully");
}
sqlite3_finalize(selectstmt);
sqlite3_close(database);
}

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 )

sqlite3_prepare_v2() == SQLITE_OK returns NO and existing table is not found

I am developing an iphone application which using sqlite3 database file. and i am using following code to select from sqlite3 database ;
NSString* dbYolu = [NSString stringWithFormat:#"%#/emhdb3.sqlite3",NSHomeDirectory()];
sqlite3* db;
NSLog(#"%# dbyolu : ", dbYolu);
if (sqlite3_open([dbYolu UTF8String], &db) == SQLITE_OK)
{
NSString *query = [NSString stringWithFormat: #"SELECT username, mobile FROM peopleto WHERE namesurname=\"%#\"", name.text];
NSLog(#"%# : query", query);
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, nil) == SQLITE_OK) // statement stmt returns null and returns SQLITE_OK = FALSE.
{
NSLog(#"stepped in SQLITE_OK is TRUE");
while (sqlite3_step(stmt) == SQLITE_ROW)
{
NSString* ders_kodu = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 0)];
double not = sqlite3_column_double(stmt, 1);
NSLog(#"%# : %f", ders_kodu, not);
}
}
else
{
NSLog(#"%# - but failed", stmt);
}
sqlite3_finalize(stmt);
}
else
NSLog(#"db could not be opened");
it fails at the "sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, nil) == SQLITE_OK" point above. and the error is : "Error:No such table : peopleto. But it successfully returns the content of table when i run this query in sql browser. I mean this query is correct and working.
btw, I get the file with pathname with the following code on viewLoad
- (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: #"emhdb3.sqlite3"]];
NSLog(#"dbpath : %#", databasePath);
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
NSLog(#"db not found");
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSLog(#"SQLITE_OK is passed");
//.... some codes here, doesn't metter for me because SQLITE_OK = true
} else {
status.text = #"Failed to open/create database";
}
}
else if ([filemgr fileExistsAtPath:databasePath] == YES)
{
NSLog(#"i found the file here : %s",[databasePath UTF8String]);
}
NSLog(#"completed");
[super viewDidLoad];
}
I have the database file in my project folder and added to the project.
What i am missing?
Thanks
///////
i am sorry for updating my question but stackoverflow does not allow me to add new ,
please find my update below ;
Here is the updated version of the code :
viewLoad part;
- (void)viewDidLoad
{
[self createEditableCopyOfDatabaseIfNeeded];
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:#"emhdb3.sqlite3"]];
NSLog(#"dbpath : %#", databasePath);
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 peopleto (pId INTEGER PRIMARY KEY AUTOINCREMENT, namesurname TEXT, mobile TEXT)";
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";
}
}
else if ([filemgr fileExistsAtPath:databasePath] == YES)
{
NSLog(#"%s is filepath",[databasePath UTF8String]);
}
NSLog(#"checkpoint 4");
[super viewDidLoad];
}
buraya başka birşey yaz
- (void)createEditableCopyOfDatabaseIfNeeded {
NSLog(#"entered createEditableCopyOfDatabaseIfNeeded");
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"emhdb3.sqlite3"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success)
{
NSLog(#"success == YES returned");
return;
}
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"emhdb3.sqlite3"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSLog( #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
else{
NSLog(#"checkpoint 2");
}
}
and the part that select query is performed ;
-(IBAction)findcontact2:(id)sender
{
NSString *dbYolu = databasePath;
sqlite3* db;
NSLog(#"%# dbyolu : ", dbYolu);
if (sqlite3_open([dbYolu UTF8String], &db) == SQLITE_OK)
{
NSString *query = [NSString stringWithFormat: #"SELECT namesurname, mobile FROM peopleto"]; //any query
NSLog(#"%# : query", query);
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, nil) == SQLITE_OK)
{
NSLog(#"SQLITE is OK");
while (sqlite3_step(stmt) == SQLITE_ROW)
{
NSString* ders_kodu = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 0)];
double not = sqlite3_column_double(stmt, 1);
NSLog(#"%# : %f", namesurname, mobile);
}
}
else
{
NSLog(#"Error=%s",sqlite3_errmsg(db)); // error message : Error=no such table: peopleto
NSLog(#"%# - is stmt", stmt); //stmt is null
}
sqlite3_finalize(stmt);
}
else
NSLog(#"could not open the db");
}
As i pointed above, the error is Error=no such table: peopleto and stmt is returned null
Are you copying your SQL file to documents, if not you need to do that first. While adding SQL file to project, it is added in your bundle and not in documents directory. YOu need to copy that first
- (void)createEditableCopyOfDatabaseIfNeeded {
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"bookdb.sql"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success)
return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"bookdb.sql"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSLog( #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
Please check the DB which is in your main bundle contains the table then try to copy it to resource folder and apply the above

SQLite issue: sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) not working

-(void)myDatabaseFunction
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"HHAuditToolDatabase.sqlite"];
if (sqlite3_open([writableDBPath UTF8String], &database) == SQLITE_OK){
NSLog(#"opening db");
NSString *keyValue;
NSString *sqlStr = #"SELECT * FROM HHAuditTable";
//following if() not working dude!!!!
//its working with !=SQLITE_OK
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
sqlite3_stmt *addStmt = nil;
if(sqlite3_prepare_v2(database,[sqlStr UTF8String], -1, &addStmt, NULL) != SQLITE_OK){
NSLog(#"%#",sqlStr);
while (sqlite3_step(addStmt) == SQLITE_ROW) {
const unsigned char *querry_returns = sqlite3_column_text(addStmt, 0);
keyValue = [[NSString alloc]initWithUTF8String:(char *) sqlite3_column_text(addStmt, 0)];
}
NSLog(#"value from DB = %#",keyValue);
That if() with comment doesn't work....Some have a cure!!! i have been on it for last 3 hrs....please come up with a soln
You are opening the database twice. You should have to close the database connection and then you have to open the database again. That is why it is not working.
Hay you can use my code its working fine for me:-
(void)myDatabaseFunction {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"flipsy.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
NSString *sql = #"SELECT * FROM HHAuditTable";
NSInteger *intvalue;
result = [[NSMutableArray alloc] init];
// NSLog(#"sql--------->%#",sql);
const char *sqlStatement = [sql UTF8String];
//if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
if(sqlite3_prepare_v2(database, sqlStatement, -1, &selectstmt , NULL)!= SQLITE_OK) {
}
else {
//NSLog(#"%#",dataTypeArray);
for(int i=0;i<[dataTypeArray count];i++) {
temp = [[NSMutableArray alloc] init];
[result addObject:temp];
// [temp release];
}
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
for(int i=0;i<[dataTypeArray count];i++) {
switch( [[dataTypeArray objectAtIndex:i] integerValue] ) {
case 0:
intvalue = (NSInteger *)sqlite3_column_int(selectstmt,i);
strvalue = [NSString stringWithFormat:#"%d",intvalue];
[[result objectAtIndex:i] addObject:(NSNumber *)strvalue];
break;
case 1:
[[result objectAtIndex:i] addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, i)]];
break;
case 2:
blob = [[NSData alloc] initWithBytes:sqlite3_column_blob(selectstmt, i) length:sqlite3_column_bytes(selectstmt, i)];
[[result objectAtIndex:i] addObject:blob];
[blob autorelease];
break;
default:
defaultValue=[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, i)];
break;
}//switch
}//for(int i=0;i<[dataTypeArray count];i++)
}//while(sqlite3_step(selectstmt) == SQLITE_ROW)
//}//else
//sqlite3_close(database);
sqlite3_finalize(selectstmt);
[temp release];
}//if (sqlite3_open([dbPath UTF
}
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"flipsy.sqlite"];
}
Please let me know if any clarification needed

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

login page problem in iphone

I'm getting the same problem, one of stackoverflow which is:
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
//const char *sql ="select Username#'%#',Password#'%#' from userinformation";
NSString *sql = [[NSString alloc] initWithFormat:#"select * from UserInformation where UserName='%#' and Password='%#' ",Username.text,Password.text];
sqlite3_stmt *selectSatement;
// Here i am getting the problem.Im not sure why sqlite3_prepare_v2 ins't meeting SQLITE_OK
if( sqlite3_prepare_v2(database, [sql UTF8String], -1, &selectSatement, NULL) == SQLITE_OK)
{
//-------------------------------------
//Loop all the
NSString *user1 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectSatement, 0)];
NSLog(#"%#",user1);
}
}
Any help with this is greatly appreciated.
First of all: if you open the database, you should also close it by using sqlite3_close(database)
I wrote in the code below an assert-statement, which will tell you, if something is wronmg with your query. Further on you might get an error, if your password or username is for some reason "nil", that's why I adapted the way you set the username and password a bit. If the value does not exist, its "0"
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
char *errorMsg;
NSString *sql = [[NSString alloc] initWithFormat: #"SELECT * FROM UserInformation WHERE UserName=\"%#\" and Password =\"%#\"", Username.text, Password.text];
if (sqlite3_exec (database, [sql UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK)
{
sqlite3_close(database);
NSAssert1(0, #"Error selecting data: %s", sqlite3_errmsg(database));
}
else
{
NSString *user1 = [NSString stringWithUTF8String:((char *)sqlite3_column_text(compiledStatement, 0) ? (char *)sqlite3_column_text(compiledStatement, 0) : (char *)"0")];
NSString *password1 = [NSString stringWithUTF8String:((char *)sqlite3_column_text(compiledStatement, 1) ? (char *)sqlite3_column_text(compiledStatement, 1) : (char *)"0")];
NSLog(#"%#: %#",user1,password1);
}
[sql release];
}
sqlite3_close(database);
What you should also keep in mind is, that the database should exist at the intended path, by calling for example the following method
-(void) checkAndCreateDatabase
{
NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:dbPath]) return;
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
[fileManager release];
}
Check the query itself, print it in log and check it by copying it from log and executing directly in the database.