login page problem in iphone - 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.

Related

sqlite3_prepare_v2 != SQLITE_OK

I wanna ask about my function below.
It print NOT AVAILABLE when I call this function.
Could you help me please??
static sqlite3 *database = nil;
static sqlite3_stmt *statement = nil;
- (BOOL) findNews:(NSString *)caption{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSLog(#"CAPTION ID : %#", caption);
NSString *querySQL = [NSString stringWithFormat:#"SELECT * FROM dbase WHERE CONTENT_ID = \"%#\"", caption];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
return YES;
}
else{
return NO;
}
sqlite3_reset(statement);
}else{
NSLog(#"NOT AVAILABLE");
}
}
return nil;
}
There are some reason for due to which the sqlite3_prepare_v2 != SQLITE_OK :
The table may not present into the database.
Wrong query statement .
Wrong column name into the query statement.
You can find the exact problem using error statement by putting following in else:
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database))
sqlite3 open. "If the filename is an empty string, then a private, temporary on-disk database will be created. This private database will be automatically deleted as soon as the database connection is closed."
So the sqlite3_open will return SQLITE_OK, if the data base not copied into Documents directory. You should copy the data into Bundle and copy this data base to Documents directory.
-(void) checkAndCreateDatabase{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:databasePath];
if(success) return;
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"mydb.sqlite"];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}

how to insert values in sqlite

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

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

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

not able to insert record in table in objective c

I made iPad application in which,
I want to insert record into database table, but I am unable to do the same.
here is my code snippet,
-(void) insertRecordIntoTableNamed: (NSString *) symbol{
NSString *sql = [NSString stringWithFormat:#"INSERT INTO recentquotes ('symbol', 'dt_tm') VALUES ('%#',datetime())",symbol];
NSLog(#"sql=%#",sql);
char *err;
if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK)
{
sqlite3_close(db);
NSAssert(0, #"Error updating table.");
}
}
my NSLog shows:
sql=INSERT INTO recentquotes ('symbol', 'dt_tm') VALUES ('PATNI',datetime())
this statement is correct, but i am unable to see VALUES PATNI and datetime() in my database table
here is rest of the code,
NSString *filePahs = Nil;
-(NSString *) filePath {
filePahs=[[NSBundle mainBundle] pathForResource:#"companymaster" ofType:#"sql"];
NSLog(#"path=%#",filePahs);
return filePahs;
}
result of above method is:
path=/Users/krunal/Library/Application Support/iPhone Simulator/5.0/Applications/9FF61238-2D1D-4CB7-8E24-9AC7CE9415BC/iStock kotak.app/companymaster.sql
-(void) openDB {
//---create database---
if (sqlite3_open([[self filePath] UTF8String], &db) != SQLITE_OK )
{
sqlite3_close(db);
NSAssert(0, #"Database failed to open.");
}
}
-(void) getAllRowsFromTableNamed: (NSString *) tableName {
//---retrieve rows---
NSString *qsql = #"SELECT * FROM recentquotes";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2( db, [qsql UTF8String], -1, &statement, nil) ==
SQLITE_OK) {
NSLog(#"b4 while");
while (sqlite3_step(statement) == SQLITE_ROW)
{
char *field1 = (char *) sqlite3_column_text(statement, 0);
NSString *field1Str = [[NSString alloc] initWithUTF8String: field1];
[recentqotarray addObject:field1Str];
[field1Str release];
}
//---deletes the compiled statement from memory---
sqlite3_finalize(statement);
NSLog(#"recentqotarray=%#",recentqotarray);
}
}
edit
i wrote this, and when i checked my log i got like this, "in find data" , i didn't got my sql=...
- (void) finddata
{
NSString *databasePath;
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
NSLog(#"in finddata");
if (sqlite3_open(dbpath, &db) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"SELECT * FROM recentquotes"];
NSLog(#"sql=%#",querySQL);
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(db, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"Inside recent quote table");
char *field1 = (char *) sqlite3_column_text(statement, 0);
NSLog(#"Column name=%s",field1);
NSString *field1Str = [[NSString alloc] initWithUTF8String: field1];
[recentqotarray addObject:field1Str];
NSLog(#"array=%#",recentqotarray);
}
sqlite3_finalize(statement);
}
sqlite3_close(db);
}
}
Thanks In Advance
In your:
NSString *sql = [NSString stringWithFormat:#"INSERT INTO recentquotes ('symbol', 'dt_tm') VALUES ('%#',datetime())",symbol];
Instead of '%#' try using \"%#\" , and check if it inserts into your db.
EDIT:
I've been working on DB a lot lately, and i've been able to successfully insert data in my sqlite, i'll write down what i use check if it helps:
NSArray*dirPath;
NSString*docDir;
dirPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docDir=[dirPath objectAtIndex:0];
databasePath=[docDir stringByAppendingPathComponent:#"example.sqlite"];
BOOL success;
NSFileManager*fm=[NSFileManager defaultManager];
success=[fm fileExistsAtPath:databasePath];
if(success)
{
NSLog(#"Already present");
}
NSString*bundlePath=[[NSBundle mainBundle] pathForResource:#"example" ofType:#"sqlite"];
NSError*error;
success=[fm copyItemAtPath:bundlePath toPath:databasePath error:&error];
if(success)
{
NSLog(#"Created successfully");
}
const char*dbPath=[databasePath UTF8String];
if(sqlite3_open(dbPath, &myDB)==SQLITE_OK)
{
NSString*insertSQL=[NSString stringWithFormat:#"insert into extable (name) values (\"%#\")",[nametextField.text]];
const char*insertStmt=[insertSQL UTF8String];
char *errmsg=nil;
if(sqlite3_exec(myDB, insertStmt, NULL, NULL, &errmsg)==SQLITE_OK)
{
NSLog(#"ADDED!");
}
sqlite3_close(myDB);
}

Query is not retrieving the data from table

im trying to integrate a database into my project.This is for first time im implementing a database project.I integrated the database into my project.Database has 3 columns named rowid,col1,col2.Below code i used for acessing the datafrom database.But it is not enetering in "if loop"Can anyone help me where im doing wrong in this case.Thanks in advance.![enter image description here][1]
/* -(void)print
{
sqlite3_stmt *statement;
qsql=[NSString stringWithFormat:#"SELECT * from light where rowid = '%d'",1];
if(sqlite3_prepare_v2(database, [qsql UTF8String], -1, &statement, NULL) == SQLITE_OK) {
NSLog(#"hhhhhhhhh");
while (sqlite3_step(statement) == (SQLITE_ROW)){
NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
// tv.text=qsql;
}
}}*/
-(void)print
{
sqlite3_stmt *statement;
//qsql=[NSString stringWithFormat:#"SELECT * from light where rowid = %d",1];
qsql=[NSString stringWithFormat:#"SELECT * from light where rowid = %i",1];
//const char *sqlStatement = [qsql cStringUsingEncoding:NSUTF8StringEncoding];
const char *qsql_stament = [qsql cStringUsingEncoding:NSUTF8StringEncoding];
if(sqlite3_prepare_v2(database, qsql_stament, -1, &statement, NULL) == SQLITE_OK) {
NSLog(#"hhhhhhhhh");
while (sqlite3_step(statement) == (SQLITE_ROW)){
// NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
NSString *Q_NO = [[NSString alloc] initWithString:[NSString stringWithFormat:#"%i",sqlite3_column_int(statement, 0)]];
// tv.text=qsql;
}
}
}
-(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];
[fileManager release];
}
-(void) openDB {
databaseName = #"Lighthr.sqlite";
NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentsPaths objectAtIndex:0];
databasePath = [documentDir stringByAppendingPathComponent:databaseName];
[self checkAndCreateDatabase];
if(sqlite3_open([databasePath UTF8String],&database) == SQLITE_OK){
NSLog(#"coming here???");
}
}
[1]: http://i.stack.imgur.com/lm1ZV.png
because rowid is always integer and you are trying to access using string.
I thing you have to try this.
Edit
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
qsql=[NSString stringWithFormat:#"SELECT * from light where rowid = %i",1];
const char *sqlStatement = [qsql cStringUsingEncoding:NSUTF8StringEncoding];
if(sqlite3_prepare_v2(database, sqlStatement, -1, &statement, NULL) == SQLITE_OK) {
NSLog(#"hhhhhhhhh");
while (sqlite3_step(statement) == (SQLITE_ROW)){
NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
// tv.text=qsql;
}
}
}
Are you trying to test without your "where" clause ?
And what is the error code return by sqlite3_prepare_v2 ?
int sql_answer = sqlite3_prepare_v2(database, qsql_stament, -1, &statement, NULL);
NSLog(#" SQL answer : %d",sql_answer );
if(sql_answer == SQLITE_OK) {
...
i think you should do in this way .
-(void)print
{
sqlite3_stmt *statement;
qsql=[NSString stringWithFormat:#"SELECT * from light where rowid = %d",1];
const char *qsql_stament = [qsql cStringUsingEncoding:NSUTF8StringEncoding];
if(sqlite3_prepare_v2(database, qsql_stament, -1, &statement, NULL) == SQLITE_OK) {
NSLog(#"hhhhhhhhh");
while (sqlite3_step(statement) == (SQLITE_ROW)){
NSString *Q_NO =[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]
}
NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
above stameny replace with below statement
NSString *Q_NO = [[NSString alloc] initWithString:[NSString stringWithFormat:#"%i",sqlite3_column_int(statement, 0)]];
and
const char *qsql_stament = [qsql cStringUsingEncoding:NSUTF8StringEncoding];
now replace [qsql UTF8String] with qsql_stament. It will work fine.