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

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

I am not familiar with the SQLite library you're using but I would recommend to switch to Core Data. cf. http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/coredata/cdprogrammingguide.html

Related

sqlite3 queries not being executed

I am working on something using SQLite3 and I cant exactly figure out why I am getting an error. I have looked at other SO post and no one can actually quite put a finger on that error and I have tried a number of things. the code is failing on this line (sqlite3_open(dbPath, &itemDB)==SQLITE_OK).
I have tried:
commenting that line and saying sqlite3_open(dbPath, &itemDB), when i do that my code excecutes but nothing in the folder
Error from the NSLog was "unable to open database file" so i created the datbase and placed it in the path myself to see if that would help but no difference
Verified the path by using breakpoints, path is correct but the db is just never created.
-(void)openDatabase
{
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *docPath=[path objectAtIndex:0];
// dbPathString=[docPath stringByAppendingPathComponent:#"items.db"];
dbPathString = [docPath stringByAppendingPathComponent:#"items.sqlite"];
char *error;
NSFileManager *fileManager=[NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:dbPathString]) {
const char *dbPath=[dbPathString UTF8String];
//Create DB
if (sqlite3_open(dbPath, &items)==SQLITE_OK)
// sqlite3_open(dbPath, &items);
{
const char *sql_stmt= " CREATE TABLE IF NOT EXIST PERSON (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,PRICE INTEGER)";
sqlite3_exec(items, sql_stmt, NULL, NULL, &error);
sqlite3_close(items);
NSLog(#"Db Created");
}
NSLog(#"%s", sqlite3_errmsg(items));
}
}
You are trying to write to the documentation directory, not the document directory.
Replace NSDocumentationDirectory with NSDocumentDirectory.
Try this tutorial
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: #"contacts.db"]];
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 CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE 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";
}
}
This will help u
#import<sqlite3.h>
-(BOOL)createTable
{
NSArray *yourArray=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath=[yourArray objectAtIndex:0];
filePath =[filePath stringByAppendingPathComponent:#"yourdatabase.sqlite"];
NSFileManager *manager=[NSFileManager defaultManager];
BOOL success = NO;
if ([manager fileExistsAtPath:filePath])
{
success =YES;
}
if (!success)
{
NSString *path2=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"yourdatabase.sqlite"];
success =[manager copyItemAtPath:path2 toPath:filePath error:nil];
}
createStmt = nil;
NSString *tableName=#"SecondTable";
if (sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
if (createStmt == nil) {
NSString *query=[NSString stringWithFormat:#"create table (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,PRICE INTEGER)];
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &createStmt, NULL) != SQLITE_OK) {
return NO;
}
sqlite3_exec(database, [query UTF8String], NULL, NULL, NULL);
return YES;
}
}
return YES;
}

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.

connect to sqlite

I'm having some issue connecting to my sqlite database.. I'm using xcode version 4.4.1
here's my code..
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: #"signature.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
status.text = #"Connected..";
} else {
status.text = #"Failed to open/create database..";
}
}
[filemgr release];
Any suggestion..?
Thanks,
Boom
There is no need to check if the database exists; sqlite3_open_v2() (reference) will create the database, if it does not exist, if you pass the flag SQLITE_OPEN_CREATE:
NSString *dbPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPath:#"signature.db"];
if (sqlite3_open_v2([dbPath UTF8String], &database, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE) == SQLITE_OK)
{
status.text = #"Connected..";
// Check the schema and install if it doesn't exist
sqlite3_close(database);
} else {
status.text = #"Failed to open/create database..";
}
You may wish to check if the DB file is in place if you have one in your app's bundle that is pre-built so you can drop it into your documents folder. Of course, as you enhance your app, any schema changes will need to be done in code. Here is some code that I use (that works, but needs to updated a bit)
When opening/creating the DB I use this to specify where the DB file will be. I don't put it with the init because my location is different between iOS and Mac OS X and I want the DB code to work with both:
NSString *dbFilePath;
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFolderPath = searchPaths[0];
dbFilePath = [documentFolderPath stringByAppendingPathComponent: #"MyDBFile.db"];
MyDB* appDB = [[EasySpendLogDB alloc] initWithFile:dbFilePath];
if(!appDB) {
// show error
return;
}
This is in my DB access class. It uses some wrapper classes I wrote:
- (id) initWithFile: (NSString*) filePathName {
if(!(self = [super init])) return nil;
BOOL myPathIsDir;
BOOL fileExists = [[NSFileManager defaultManager]
fileExistsAtPath: filePathName
isDirectory: &myPathIsDir];
NSString *backupDbPath = [[NSBundle mainBundle]
pathForResource:#"MyDBFile"
ofType:#"db"];
if (backupDbPath != nil && !fileExists) {
[[NSFileManager defaultManager]
copyItemAtPath:backupDbPath
toPath:filePathName
error:nil];
}
db = [[ABSQLiteDB alloc] init];
if(![db connect:filePathName]) {
return nil;
}
[self checkSchema]; // this is where schema updates are done (see project sample)
return self;
}
You may also want to check out this objective-c wrapper I wrote that has a sample project: https://github.com/AaronBratcher/ABSQLite

How much data available in table using row count not working

I want to check at the load time of application whether data is available or not in the table so for that I using following code on the viewload of my first file if available then move to other file else retain same but it can't give perfect result mainly row count is not working
NSString *dbPath;
NSString *docsDir;
NSArray *dirPath;
int count=0;
dirPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir=[dirPath objectAtIndex:0];
dbPath=[[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:#"TimerDataBaseMain.db"]];
NSFileManager *fileManager=[NSFileManager defaultManager];
if([fileManager fileExistsAtPath: dbPath] == YES)
{
const char *databsPath=[dbPath UTF8String];
NSLog(#"from created;");
if(sqlite3_open(databsPath,&sqlDatabase) == SQLITE_OK)
{
const char *query="SELECT COUNT(*) FROM PRJDATA";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(sqlDatabase, query, -1, &statement, NULL)==SQLITE_OK) {
while(sqlite3_step(statement)==SQLITE_ROW)
{
count++;
NSLog(#"from count");
}
NSLog(#"from row count");
}
sqlite3_finalize(statement);
}
sqlite3_close(sqlDatabase);
}
if (count>0) {
ListEventCreated *listObject=[[ListEventCreated alloc] initWithNibName:#"ListEventCreated" bundle:[NSBundle mainBundle]];
listObject.title=#"List of event";
NSLog(#"from if condition");
NSLog(#"%i",count);
[self.navigationController pushViewController:listObject animated:YES];
[listObject release];
listObject=nil;
}
I believe , this is WRONG
SELECT COUNT(*) PRJDATA
You should use this
SELECT COUNT(*) FROM PRJDATA

How do I insert some data into an Sqlite 3 database

Through the following code I am retrieving data from a Db, however I need to insert some data into a Sqlite3 database with this code before select statement. Can any one tell me where I need to put the insert query and how can I execute it.
I am selecting the datas through the following code:
sqlite3* database;
- (void)initializeDatabase
{
list=[[NSMutableArray alloc] init];
BOOL success;
NSFileManager *filemanager=[NSFileManager defaultManager];
NSError *error;
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory= [paths objectAtIndex:0];
NSString *writablePath=[documentsDirectory stringByAppendingPathComponent:#"SymbolTalk.sqlite"];
success=[filemanager fileExistsAtPath:writablePath];
if(!success)
{
NSString *defaultDBPath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"SymbolTalk.sqlite"];
success=[filemanager copyItemAtPath:defaultDBPath toPath:writablePath error:&error];
if(!success)
{
NSAssert1(0,#"Failed to create writable databasefile withw message %#.",[error localizedDescription]);
}
}
//Specify where to get the database from
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory= [paths objectAtIndex:0];
NSString *path=[documentsDirectory stringByAppendingPathComponent:#"SymbolTalk.sqlite"];
//Open the database
//might have to make database as property
if(sqlite3_open([path UTF8String], &dataBase) ==SQLITE_OK)
{
const char *sql="select filename from scenes";
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)]];
}
}
}
}
sqlite3_stmt *insert_statement = nil;
const char *sql = "INSERT INTO scenes (filename) VALUES(?)";
if (sqlite3_prepare_v2(database, sql, -1, &insert_statement, NULL) != SQLITE_OK) {
NSAssert1(NO, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
sqlite3_bind_text(insert_statement, 1, [newFilename UTF8String], -1, SQLITE_TRANSIENT);
if (sqlite3_step(insert_statement) == SQLITE_DONE) {
// code if all ok
} else {
NSAssert1(NO, #"Error: failed to insert into the database with message '%s'.", sqlite3_errmsg(database));
}
sqlite3_reset(insert_statement);
sqlite3_finalize(insert_statement);