Query is not retrieving the data from table - iphone

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.

Related

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

sqlite, select query doesn't work

- (UserInfo*)getCurrentUserInfo:(NSString*)userName
{
UserInfo *userInfo = [[UserInfo alloc]init];
sqlite3 *database;
sqlite3_stmt *selectstmt;
NSLog(#"userName:%#",userName);
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSString *sqlString = [NSString stringWithFormat:#"SELECT USER_LEVEL FROM USER_INFO WHERE USER_NAME = '%#'" , userName];
NSLog(#"getCurrentUserInfo:%#",sqlString);
const char *SqlCommand = [sqlString UTF8String];
if (sqlite3_prepare_v2(database, SqlCommand, -1, &selectstmt, NULL) == SQLITE_OK) {
NSLog(#"success!");
while (sqlite3_step(selectstmt) == SQLITE_ROW) {
NSString *userInfoStr = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
NSLog(#"select result:%#",userInfoStr);
}
}
sqlite3_finalize(selectstmt);
}
sqlite3_close (database);
return userInfo;
}
the following is my log output:
2012-03-06 17:50:11.556 MagicWords[508:f803] userName:Tan
2012-03-06 17:50:11.557 MagicWords[508:f803] getCurrentUserInfo:SELECT USER_LEVEL FROM USER_INFO WHERE USER_NAME = 'Tan'
It doesn't print "success",so sqlite3_prepare_v2 don't return yes.but my database is ok:
I can't find the problem?
Add sqlite error message . It will give an insight of what is going on inside. If all about your database is correct ,check the table name.
UserInfo *userInfo = [[UserInfo alloc]init];
sqlite3 *database;
sqlite3_stmt *selectstmt;
NSLog(#"userName:%#",userName);
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSString *sqlString = [NSString stringWithFormat:#"SELECT USER_LEVEL FROM USER_INFO WHERE USER_NAME = '%#'" , userName];
NSLog(#"getCurrentUserInfo:%#",sqlString);
const char *SqlCommand = [sqlString UTF8String];
if (sqlite3_prepare_v2(database, SqlCommand, -1, &selectstmt, NULL) == SQLITE_OK) {
NSLog(#"success!");
while (sqlite3_step(selectstmt) == SQLITE_ROW) {
NSString *userInfoStr = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
NSLog(#"select result:%#",userInfoStr);
}
}
//Add the error message here.
else
{
NSLog(#"%s",sqlite3_errmsg(database));
}
///////
sqlite3_finalize(selectstmt);
}
sqlite3_close (database);
return userInfo;
Remove the quotes inside ' ' and Use Semicolon at the end of the sqlString.
NSString *sqlString = [NSString stringWithFormat:#"SELECT USER_LEVEL FROM USER_INFO WHERE USER_NAME = %#;" , userName];
try this when you are converting sqlString to char
const char *SqlCommand = (char *)[sqlString
cStringUsingEncoding:NSUTF8StringEncoding];

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

How to retrieve a particular column from a database in iphone

in my project im using a database.There are almost 365 questions in that.so i want to get a particulat question for a particular day.i used the code below to fetch a qusestion from database.
-(void)print{
sqlite3_stmt *statement;
// SELECT * from light where rowid = %i",1
qsql=[NSString stringWithFormat:#"Select * from ishh where col_1 = '365'"];
if(sqlite3_prepare_v2(database, [qsql UTF8String], -1, &statement, NULL) == SQLITE_OK) {
NSLog(#"%dsssssssssssssss",sqlite3_step(statement));
NSLog(#"%ddddddddddddddddddddd", (SQLITE_ROW));
NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
NSLog(#"%# gg",Q_NO);
when i use the above code it is printing the correct question from database.Also when i give the statement like qsql=[NSString stringWithFormat:#"Select * from ishh where col_1 = '1'"]; it is not fetching the question.
But when i use the below code it is not fetching from the database.
-(void)print{
sqlite3_stmt *statement;
// SELECT * from light where rowid = %i",1
qsql=[NSString stringWithFormat:#"Select * from ishh where col_1 = '1'"];
if(sqlite3_prepare_v2(database, [qsql UTF8String], -1, &statement, NULL) == SQLITE_OK) {
NSLog(#"%dsssssssssssssss",sqlite3_step(statement));
NSLog(#"%ddddddddddddddddddddd", (SQLITE_ROW));
NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
NSLog(#"%# gg",Q_NO);
while (sqlite3_step(statement) == (SQLITE_ROW))
{
NSLog(#" iolo");
NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
//NSString *Q_NO = [[NSString alloc] initWithString:[NSString stringWithFormat:#"%i",sqlite3_column_int(statement, 0)]];
NSLog(#"%# gg",Q_NO);
}
sqlite3_reset(statement);
}
sqlite3_finalize(statement);
}
Can anyone tell me where im going wrong.Thanks in advance.
-(void)print{
sqlite3_stmt *statement;
qsql=[NSString stringWithFormat:#"Select * from ishh where col_1 = '1'"];
if(sqlite3_prepare_v2(database, [qsql UTF8String], -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == (SQLITE_ROW))
{
char *field0 = (char *)sqlite3_column_text(statement, 0);
char *field1 = (char *)sqlite3_column_text(statement, 1);
NSString *Q_NO = nil;
if(field0!=NULL){
Q_NO = [[NSString alloc] initWithUTF8String:field0];
}
NSString *Q_NO1 = nil;
if(field1!=NULL){
Q_NO1 = [[NSString alloc] initWithUTF8String:field1];
}
NSLog(#"%# %#",Q_NO, Q_NO1);
[Q_NO release];
[Q_NO1 release];
}
}
sqlite3_finalize(statement);
}

Accessing an object through SQLIte database

I am passing an object to the method in which I am executing a query. My method is:
-(BOOL)searchWordInDatabase:(NSString *)string
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory= [paths objectAtIndex:0];
NSString *path=[documentsDirectory stringByAppendingPathComponent:#"SymbolTalkLanguageElement.sqlite"];
//Open the database
//might have to make database as property
if(sqlite3_open([path UTF8String], &dataBase) ==SQLITE_OK)
{
const char *sql="select ImageName from tblLanguageElement where Category= string";
sqlite3_stmt *statement;
if(sqlite3_prepare(dataBase, sql, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]);
//[list addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]];
return YES;
}
}
}
return NO;
}
But I am not getting the value of the String in the query. How can I do it?
There is a mistake in your query. You can not substitute a string like that. Do it in the following way.
NSString *sqlStr = [NSString stringWithFormat:#"select ImageName from tblLanguageElement where Category = '%#'", string];
char *sql = (char *)[sqlStr UTF8String];
Make sure that your database exists at that path you retrieve. And you can bind string variables as follows while executing statements.
const char *sql = "select ImageName from tblLanguageElement where Category = ?";
sqlite3_stmt *statement;
if(sqlite3_prepare(dataBase, sql, -1, &statement, NULL) == SQLITE_OK)
{
sqlite3_bind_text(statement, 1, [string UTF8String], -1, SQLITE_TRANSIENT);
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]);
//[list addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]];
return YES;
}
}