I am working with the communication of sqlite database from one viewcontroller to another, but some how i am not getting the database on the second view controller. Bellow is the code which i am using for it.:-
On First View controller
//Creating a table of MOtivational Thoughts
dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPath objectAtIndex:0];
Second.databasePath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"S.H.E.D_DB"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([ filemgr fileExistsAtPath: Second.databasePath] == NO) {
const char *dbpath = [Second.databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS THOUGHTS (ID integer ,Motivation_Thaought TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"Failed to create table");
}
else
{
NSLog(#" created table");
}
sqlite3_close(contactDB);
} else {
}
}
// Fetching Data from table of MOtivational Thoughts
if(sqlite3_open([Second.databasePath UTF8String], &contactDB) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
int randomNumber = [self getRandomNumberBetween:0 to:6];
NSString *queryString = [NSString stringWithFormat:#"Select * FROM THOUGHTS where ID= '%d'",randomNumber];
const char* sql = [queryString UTF8String];
NSLog(#"path value : %#", Second.databasePath);
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(contactDB, sql, -1, &compiledStatement, nil)==SQLITE_OK) {
// Loop through the results and add them to the feeds array
NSLog(#"Ready to enter while loop");
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSLog(#"reading");
NSString *aid = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
motivationView.text = aid;
NSLog(#"Thought of the day %#", aid);
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(contactDB);
// Do any additional setup after loading the view from its nib.
}
On Second View Controller
NSLog(#"path value : %#", databasePath);
if(sqlite3_open([databasePath UTF8String], &contactDB) == SQLITE_OK){
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS SHEDSLIST (SHED_ID integer ,SHED_Name TEXT ,SHED_Description TEXT, SHED_TIME DATETIME)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"Failed to create table");
}
else
{
NSLog(#" created table");
}
sqlite3_close(contactDB);
} else {
}
PLease locate my error and give me sutable solution.
May be you should access the database path as self.databasePath in SecondViewController because I believe you have created a property for that. Instead of that you are trying to access some instance variable databasePath. Look at your following code in FirstViewController:
Second.databasePath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"S.H.E.D_DB"]];
Related
I checked from sqlitebrowser that I successfully created sqlite and inserted data to sqlite, but now my problem is I could not read data from sqlite. I am new to sqlite.
Should I open the sqlite first, and read it? Where is wrong on my code below?
This code for open the existing sqlite.
-(void)openSqlite{
NSString *docsDir = [NSString stringWithFormat:#"Questiondata.db"];
NSArray *dirPaths;
_databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:#"Questiondata.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:_databasePath] == NO) {
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK) {
char *errorMessage;
const char *sql_statement ="CREATE TABLE IF NOT EXISTS users (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
if (sqlite3_exec(_contactDB,sql_statement,NULL,NULL,&errorMessage) != SQLITE_OK) {
NSLog(#"Failed to create the table");
}
sqlite3_close(_contactDB);
}
else{
NSLog(#"Fail to open/create the table");
}
}
}
This is code for read data from existing sqlite.
-(void)readData{
NSLog(#"we came here");
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB)) {
NSString *querySQL = [NSString stringWithFormat:#"SELECT * FROM Questions WHERE QuestionNumber = 1"];
const char*query_statement = [querySQL UTF8String];
if (sqlite3_prepare_v2(_contactDB, query_statement, -1, &statement, NULL)== SQLITE_OK) {
if (sqlite3_step(statement) == SQLITE_ROW) {
NSString *addressfield = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement,0)];
NSLog(#"finddata:%#",addressfield);
}else{
NSLog(#"notfinddatabase");
}
sqlite3_finalize(statement);
}else{
NSLog(#"failed to serache database");
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
NSLog(#"not be here");
}
}
In openSqlite method
const char *sql_statement ="CREATE TABLE IF NOT EXISTS users (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
and in your query
NSString *querySQL = [NSString stringWithFormat:#"SELECT * FROM Questions WHERE QuestionNumber = 1"];
table name and column name are not same.
Change in Place "Questions" with "users" .
and also change "QuestionNumber" with the table column.
May be, it will helps you or feel free.
sqlite doesn't report all errors until you start accessing the data. For example just about any filename and path will pass without errors.
First of all you must check that, the database is in the Documents folder?
It's not there by default.
Perhaps it's in the main bundle?
Try this:
NSString *dbName = [[NSBundle mainBundle] pathForResource:#"dbFile" ofType:#"db"];
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am using SQLite DB in my iOS app. In my screen 1, I was successfully able to create a Database, a table, insert into it and retrieve from it.
However from screen 2 when I am trying to create a table in the same database and insert values, I am unable to.
This is the code which I am using.
-(void) 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:
#"coning.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 order (ID INTEGER PRIMARY KEY AUTOINCREMENT , NAME TEXT UNIQUE , ADDRESS TEXT UNIQUE, PHONE TEXT UNIQUE)";
if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"Failed to create table");
}
sqlite3_close(_contactDB);
} else {
NSLog(#"Failed to open/create database");
}
}
}
- (void)saveData {
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT OR REPLACE INTO order (name, address, phone) VALUES (\"%#\", \"%#\", \"%#\")",
#"name", #"address", #"phone"];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_contactDB, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"added");
} else {
NSLog(#"Failed to add contact");
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
}
}
I have been using the same code to add entries in table 1 but when I do the same to create table 2, its says 'Failed to add contact'. Can someone suggest where I might be going wrong?
Also I want to make the PK of table 1 as a FK in table 2.
You can use sqlite3_exec() method instead of sqlite3_step().
sqlite3_exec() will execute whatever the query you have given.
I am sure, It will definitely help you.
-(BOOL)createNewTableInExistingDb
{
NSArray *array=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath=[array objectAtIndex:0];
filePath =[filePath stringByAppendingPathComponent:#"database.db"];
NSFileManager *manager=[NSFileManager defaultManager];
BOOL success = NO;
if ([manager fileExistsAtPath:filePath])
{
success =YES;
}
if (!success)
{
NSString *path2=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"database.db"];
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 %#(RegNo integer, name text)",tableName];
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;
}
this is what i am doing in header
static sqlite3 *database = nil;
static sqlite3_stmt *deleteStmt = nil;
#implementation SQLAppDelegate
#synthesize window;
#synthesize navigationController;
#synthesize coffeeArray;
this is what i am using for deleting raw
- (void) removeCoffee:(NSNumber *)coffeeObj {
NSLog(#"coffeeObj%#",coffeeObj);
int myInteger = [coffeeObj integerValue];
NSLog(#"myInteger%d",myInteger);
// print this myInteger0
NSLog(#"%#",coffeeArray);
//print object
if (sqlite3_open([self getDBPath], &database) == SQLITE_OK)
{
NSLog(#"myInteger%#",[self getDBPath]);
NSString *sql = [NSString stringWithFormat: #"delete from Coffee where CoffeeID =%d",myInteger];
const char *del_stmt = [sql UTF8String];
NSLog(#"%#",del_stmt); // getting print
// print this delete from Coffee where CoffeeID =0.
sqlite3_prepare_v2(database, del_stmt, -1, & deleteStmt, NULL);
NSLog(#"sqlite3_step(deleteStmt) == SQLITE_DONE%#",sqlite3_step(deleteStmt) == SQLITE_DONE);
// this print null
if (sqlite3_step(deleteStmt) == SQLITE_DONE)
{
//NSLog(#"hi") this is not getting print
} else {
//NSLog(#"hi") this is getting print
}
sqlite3_finalize(deleteStmt);
sqlite3_close(database);
[coffeeArray removeObjectAtIndex:myInteger];
NSLog(#"%#",coffeeArray);
// object is deleted
}
}
my table is like below
table name = Coffee
CoffeeID(INTEGER)=0
CoffeeName(VARCHAR)=Latte
Price(REAL)=2.99
where thing runs perfectly object get deleted from array and thats why its not appearing on table cell. but its not getting deleted from database table thats why it when i launch app again then it shows again please help what i am doing wrong.
Before start deleting the object just conform once the database is opened properly or not. Just try like this.
//Setting path
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"database.db"]];
const char *dbpath=[databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *sql = [NSString stringWithFormat: #"delete from Coffee where CoffeeID =%d",myInteger];
const char *del_stmt = [sql UTF8String];
sqlite3_prepare_v2(database, del_stmt, -1, & deleteStmt, NULL);
if (sqlite3_step(deleteStmt) == SQLITE_DONE)
{
} else {
}
sqlite3_finalize(deleteStmt);
sqlite3_close(database);
[coffeeArray removeObjectAtIndex:myInteger];
NSLog(#"%#",coffeeArray);
// object is deleted
}
if(sqlite3_open([[self filepath] UTF8String], &db) == SQLITE_OK)
{
Deletestatement = nil;
if(Deletestatement == nil)
{
const char *sql = "delete from Sqlitemanager2;";
if(sqlite3_prepare_v2(db, sql, -1, &Deletestatement, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating delete statement. '%s'", sqlite3_errmsg(db));
}
if (SQLITE_DONE != sqlite3_step(Deletestatement)) //prathibha for problem in if
NSAssert1(0, #"Error while deleting. '%s'", sqlite3_errmsg(db));
sqlite3_finalize(Deletestatement);
}
I hope this will help you.
Could someone be so kind as to fill in the few missing pieces of code below. I am struggling with executing an sqlite statement using sqlite3_step, iterating through each row of results and putting the data into a useable format.
Here is the code that creates the database (Database is only two colums)
// Check if database is setup, if not create it
NSString *documents_directory;
NSArray *directory_path;
// Get the documents directory
directory_path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documents_directory = [directory_path objectAtIndex:0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString: [documents_directory stringByAppendingPathComponent: #"weights.db"]];
NSFileManager *file_manager = [NSFileManager defaultManager];
// Create database if it doesn't already exist
if([file_manager fileExistsAtPath: databasePath ] == NO){
const char *database_path = [databasePath UTF8String];
if(sqlite3_open(database_path, &contactDB) == SQLITE_OK){
char *error_message;
const char *sql_statement = "CREATE TABLE IF NOT EXISTS RECORDED_WEIGHTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, WEIGHT TEXT, TIME TEXT)";
if(sqlite3_exec(contactDB, sql_statement, NULL, NULL, &error_message) != SQLITE_OK){
status.text = #"Failed to create table";
}
sqlite3_close(contactDB);
}else{
status.text = #"Failed to open/create database";
}
}
And here is the code I am trying to complete;
// Get info from database and load it.
const char *database_path = [databasePath UTF8String];
sqlite3_stmt *statement;
if(sqlite3_open(database_path, &contactDB) == SQLITE_OK){
NSString *SQLquery = [NSString stringWithFormat:#"SELECT * FROM RECORDED_WEIGHTS ORDER BY TIME DESC"];
const char *query_statement = [SQLquery UTF8String];
if(sqlite3_prepare_v2(contactDB, query_statement, -1, &statement, NULL) == SQLITE_OK){
// Please help me execute statement and get results into useable format here.
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
Thanks in advance.
You want to do something like this:
while(sqlite3_step(statement) == SQLITE_ROW)
{
// int value
int intValue = sqlite3_column_int(statement,fieldIndex);
// string value
NSString* stringValue;
if (sqlite3_column_type(dbps, fieldIndex) != SQLITE_NULL)
{
const char *c = (const char *)sqlite3_column_text(dbps, fieldIndex);
if (c)
{
stringValue = #(c);
}
}
... etc...
}
Look at the documents for the different column types. You can also look at different objective-c wrappers out there to get an idea of how to access the database.
Hi i have made a function in my app delegate to remove the redundancy of my database , I am not sure do i have coded right as i have to perform nesting of SQL statements to find out the error in DB.
Can any body suggest me where i am wrong because the application is running well in simulator and crashing in Device.
I am even Not Sure where to Put finalize and sqlite3_close . Kindly help
-(void) removeRedundancy2
{
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
dbPathString = [[docPaths objectAtIndex:0] stringByAppendingPathComponent:#"turfnutritiontool_ver_99.db"];
sqlite3_stmt *selectStmt;
sqlite3_stmt *selectStmt1;
BOOL isMyFileThere = [[NSFileManager defaultManager] fileExistsAtPath:dbPathString];
if (isMyFileThere)
{
if (sqlite3_open([dbPathString UTF8String], &database1)==SQLITE_OK)
{
// TO REMOVE FROM from tnt_scenario_product when NO ProductID Found
NSString *querySql2= [NSString stringWithFormat:#"SELECT productid from tnt_scenarioproduct"];
const char* query_sql2 = [querySql2 UTF8String];
if(sqlite3_prepare_v2(database1, query_sql2, -1, &selectStmt, NULL) == SQLITE_OK)
{
while (sqlite3_step(selectStmt) == SQLITE_ROW)
{
int productid = sqlite3_column_int(selectStmt, 0);
// NSLog(#"ProductId1 =%d",productid);
NSString *querySql21= [NSString stringWithFormat:#"SELECT productid from tnt_productcontent WHERE productid = %d",productid];
const char* query_sql21 = [querySql21 UTF8String];
if(sqlite3_prepare_v2(database1, query_sql21, -1, &selectStmt1, NULL) == SQLITE_OK)
{
if (sqlite3_step(selectStmt1) == SQLITE_ROW)
{
// DO NOTHING
}
else
{ // to delete scenario without product id
NSLog(#"Delete this Product from TPC 2 %d",productid);
NSString *querydelete2= [NSString stringWithFormat:#"DELETE from tnt_scenarioproduct WHERE productid = %d",productid];
const char* query_delete2 = [querydelete2 UTF8String];
char *error;
sqlite3_exec(database1, query_delete2, NULL, NULL, &error);
NSLog(#"error=%s ",error);
sqlite3_finalize(selectStmt1);
}
}
sqlite3_finalize(selectStmt1);
sqlite3_close(database1);
}
sqlite3_finalize(selectStmt);
}
sqlite3_close(database1);
}
sqlite3_close(database1);
}
}
After calling sqlite3_open, you must call sqlite3_close for that connection exactly once.
After calling sqlite3_prepare_v2, you must call sqlite3_finalize for that statement exactly once.
if (sqlite3_open([dbPathString UTF8String], &database1)==SQLITE_OK)
{
...
if(sqlite3_prepare_v2(database1, query_sql21, -1, &selectStmt1, NULL) == SQLITE_OK)
{
...
}
sqlite3_finalize(selectStmt);
....
}
sqlite3_close(database1);
Furthermore, you should not reuse the same variable (selectStmt) for two different queries to prevent confusion about its lifetime.