Invalid SQLite table on iPhone? - iphone

I've been trying to access an SQLite3 database via my iphone, but I keep on getting "no such table: user_info" as an error.
So, here are the steps I've gone through:
Create the database via command line:
sqlite3 users.sqlite
create table user_info (name text, info text);
insert into user_info value('Name1', 'This is info for Name1');
select * from user_info;
[result]: Name1|This is info for Name1
select * from sqlite_master;
[result]: table|user_info|user_info|3|CREATE TABLE user_info (name text, info text)
Copy this into the resources folder in XCode, with the option to copy it to the appropriate directory.
Attempt to access it and get the error "no such table: user_info".
Okay, so how am I doing #3? Well, I've updated a bit, so now I try to create the table if it's non-existent. Here is my current code:
static NSString *dbname = #"users.sqlite";
-(NSString *) dbFilePath {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES
);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *dbPath = [documentsDir stringByAppendingPathComponent:dbname];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if (!success) {
fprintf(stderr, "Database is not writeable!\n");
}
return dbPath;
}
- (void)createEditableCopyOfDatabaseIfNeeded {
BOOL success;
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *writeableDBPath = [self dbFilePath];
success = [fileManager fileExistsAtPath:writeableDBPath];
if (success) {
return;
}
NSString *defaultDBPath =
[[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:dbname];
success = [fileManager
copyItemAtPath:defaultDBPath
toPath:writeableDBPath
error:&error];
if (!success) {
fprintf(stderr, "Failed to create writable database file\n");
}
}
-(void) openDB {
if (sqlite3_open([[self dbFilePath] UTF8String], &db) != SQLITE_OK) {
sqlite3_close(db);
fprintf(stderr, "Database failed to open.\n");
}
}
-(void) createTableIfNeeded {
NSString *result = #"";
sqlite3_stmt *statement;
char *sql = sqlite3_mprintf(
"CREATE TABLE IF NOT EXISTS user_info (name text info text);"
);
dbresult = sqlite3_prepare_v2(db, sql, strlen(sql), &statement, NULL);
if (SQLITE_OK != dbresult) {
NSAssert1(0, "no user_info table!", nil);
fprintf(
stderr,
"Error in preparation of query: %s\n",
sqlite3_errmsg(db)
);
sqlite3_close(db);
return;
}
sqlite3_finalize(statement);
sqlite3_free(sql);
}
- (NSString *)getDatabaseEntry:(NSString *)i_name {
NSString *result = #"";
sqlite3_stmt *statement;
char *sql = sqlite3_mprintf(
"SELECT 'info' FROM 'user_info' WHERE name='%q'",
[i_name cStringUsingEncoding:NSASCIIStringEncoding]
);
dbresult = sqlite3_prepare_v2(db, sql, strlen(sql), &statement, NULL);
if (SQLITE_OK != dbresult) {
fprintf(
stderr,
"Error in preparation of query: %s\n",
sqlite3_errmsg(db)
);
sqlite3_close(db);
return result;
}
dbresult = sqlite3_step(statement);
if (SQLITE_ROW == dbresult) {
char *nfo = (char *)sqlite3_column_text(statement, 0);
result = [NSString stringWithUTF8String:nfo];
}
sqlite3_finalize(statement);
sqlite3_free(sql);
return result;
}
// viewDidAppear
- (void)viewDidAppear:(BOOL)animated {
[self createEditableCopyOfDatabaseIfNeeded];
[self openDB];
[self createTableIfNeeded];
}
// Later, when I have a valid user:
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker
shouldContinueAfterSelectingPerson:(ABRecordRef)person {
...
NSString *nfo = [self getDatabaseEntry:name.text];
...
}
I've been against this wall for a couple of days now, so any help is greatly appreciated.

Well, I fixed it, but I'm not certain on how.
I created a blank project and followed the tutorial here:
http://www.raywenderlich.com/913/sqlite-101-for-iphone-developers-making-our-app
And made sure that worked. (It did.)
I then used the bit from here:
http://www.raywenderlich.com/725/how-to-read-and-write-xml-documents-with-gdataxml
To copy the database into a location where it's writeable. I had very similar code before.
So now it works.
I built a new table specifically with the "sqlite3" extensions. I don't know if this actually makes a difference or not.
I also used:
[[NSBundle mainBundle] pathForResource:#"users" ofType:#"sqlite3"];
As opposed to:
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbname];
Again, no idea if this matters or not.
Hopefully this helps someone else out!
//----------------------------------------------------------------------------
-(NSString *) dbFilePath {
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *dbPath = [documentsDir stringByAppendingPathComponent:#"users.sqlite3"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if (!success) {
fprintf(stderr, "Database is not writeable! Attempting to create writeable database.\n");
NSString *bundle_path = [[NSBundle mainBundle] pathForResource:#"users" ofType:#"sqlite3"];
success = [fileManager copyItemAtPath:bundle_path toPath:dbPath error: &error];
if (!success) {
fprintf(stderr, "Failed to create writeable database file\n");
}
}
return dbPath;
}
//----------------------------------------------------------------------------
-(void) openDB {
if (sqlite3_open([[self dbFilePath] UTF8String], &db) != SQLITE_OK) {
sqlite3_close(db);
NSAssert(0, #"Database failed to open.");
fprintf(stderr, "Database failed to open.\n");
}
}
//----------------------------------------------------------------------------
- (NSString *)getDatabaseEntry:(NSString *)i_name {
NSString *result = #"";
sqlite3_stmt *statement;
char *sql = sqlite3_mprintf(
"SELECT info FROM user_info WHERE name='%q'",
[i_name cStringUsingEncoding:NSASCIIStringEncoding]
);
dbresult = sqlite3_prepare_v2(db, sql, strlen(sql), &statement, NULL);
if (SQLITE_OK != dbresult) {
fprintf(stderr,
"Error in preparation of query: %s\n",
sqlite3_errmsg(db));
sqlite3_close(db);
sqlite3_free(sql);
return result;
}
dbresult = sqlite3_step(statement);
if (SQLITE_ROW == dbresult) {
char *nfo = (char *)sqlite3_column_text(statement, 0);
result = [NSString stringWithUTF8String:nfo];
}
sqlite3_finalize(statement);
sqlite3_free(sql);
return result;
}

Related

how can i update sqlite database

I want to update records from several textfiels in detail viewcontroller, but when I cliCk on update button, its goes to failed to update database. pls suggest me.
-(IBAction)updateQuery:(id)sender
{
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &Information) == SQLITE_OK)
{
NSString *updateSQL = [NSString stringWithFormat: #"update CONTACTS set address=\"%#\",phone=\"%#\",imageUrl=\"%#\" WHERE name=\"%#\"",daddress.text,dphone.text,durl.text,dname.text];
const char *update_stmt = [updateSQL UTF8String];
sqlite3_prepare_v2(Information, update_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
dstatuslabel.text=#"updated successfully";
}
else
{
dstatuslabel.text = #"Failed to update contact";
}
sqlite3_finalize(statement);
sqlite3_close(Information);
}
}
NSString *updateSQL = [NSString stringWithFormat: #"update CONTACTS set address='%#',phone='%#',imageUrl='%#' WHERE name='%#'",daddress.text,dphone.text,durl.text,dname.text];
In my method i use following way its working :
-(BOOL)updateProfileFromCreatorId:(int)creatorProfileId{
char *st,*errorMsg;
NSLog(#"profile.creatorProfileId:%d",creatorProfileId);
st = sqlite3_mprintf("UPDATE Profile SET `CreatorID`=%d WHERE `CreatorID`= 1"
,creatorProfileId //username
);
NSLog(#"updateQUERY: %#",[NSString stringWithUTF8String:st]);
int ret = sqlite3_exec(rlraDb, st, NULL, NULL, &errorMsg);
if (ret != SQLITE_OK) {
sqlite3_free(errorMsg);
sqlite3_free(st);
return NO;
}
sqlite3_free(st);
return YES;
}
Add the Sqlite DB like any other file in your application bundle
Copy it to documents directory via code and use it (Method :checkAndCreateDatabase ) .The purpose of this is that updating content in sqlite is possible in Documents directory only
-(void) checkAndCreateDatabase
{
// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:_databasePath];
// If the database already exists then return without doing anything
if(success) return;
// If not then proceed to copy the database from the application to the users filesystem
// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:_databaseName];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:_databasePath error:nil];
}
- (id)init {
if ((self = [super init]))
{
_databaseName = DB_NAME;
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
_databasePath = [documentsDir stringByAppendingPathComponent:_databaseName];
if (sqlite3_open([[self dbPath] UTF8String], &_database) != SQLITE_OK)
{
[[[UIAlertView alloc]initWithTitle:#"Missing"
message:#"Database file not found"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil]show];
}
}
return self;
}
Try this...It should work...
1) Please make sure you are copying the db from your bundle to documents directory before updating the db...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"YOUR DBNAME.sqlite"];
// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:filePath];
// If the database already exists then return without doing anything
if(success) return;
// If not then proceed to copy the database from the application to the users filesystem
// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:_databaseName];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:_databasePath error:nil];
}
2)Step 2: Update
sqlite3 *database;
sqlite3_stmt *updateStmt=nil;
const char *dbpath = [filePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *updateSQL = [NSString stringWithFormat: #"update CONTACTS set address=\"%#\",phone=\"%#\",imageUrl=\"%#\" WHERE name=\"%#\"",daddress.text,dphone.text,durl.text,dname.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &updateStmt, NULL);
if (sqlite3_step(updateStmt) == SQLITE_DONE)
{
NSLog(#"updated");
}
}

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

sqlite3_prepare error #26

I have following code (modified code from this tutorial):
-(NSMutableArray *) getChampionDatabase
{
NSMutableArray *championsArray = [[NSMutableArray alloc] init];
#try {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *databasePath = [[NSBundle mainBundle]pathForResource: #"Champions Database" ofType:#"sqlite"];
BOOL success = [fileManager fileExistsAtPath:databasePath];
if (!success)
{
NSLog(#"cannot connect to Database! at filepath %#",databasePath);
}
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
const char *sql = "SELECT CHAMPION_ID,CHAMPION_NAME,CHAMPION_IMG FROM CHAMPIONS";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(database, sql, -1, &sqlStatement, NULL) == SQLITE_OK)
{
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
championList *ChampionList = [[championList alloc]init];
ChampionList.championId = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,0)];
ChampionList.championName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
ChampionList.championImage = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 2)];
[championsArray addObject:ChampionList];
}
}
else
{
NSLog(#"problem with database prepare");
}
}
else
{
NSLog(#"problem with database openning");
}
}
#catch (NSException *exception)
{
NSLog(#"An exception occured: %#", [exception reason]);
}
#finally
{
return championsArray;
}
}
After running this code i always have output : "problem with database prepare"
Then i tried to check error number of sqlite3_prepare by following code:
int ret = sqlite3_prepare(database, sql, -1, &sqlStatement, NULL);
if (ret != SQLITE_OK) {
NSLog(#"Error calling sqlite3_prepare: %d", ret);
}
output: "Error calling sqlite3_prepare: 26"
error 26 - /*File opened that is not a database file */
File have sqlite 3 version
how is this possible? file extension is .sqlite and i can modify it in sqlite manager
Make sure you added your DB to the ressource bundle of your project and don't put any space in your name of your DB. For example use a name like champion_db.sqlite.

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

create sqlite db programmatically in iphone sdk

hai i a'm trying to create a sqlite database programmatically at the run time. can anybody say how to create it in iphone sdk.
Just call the sqlite3_open function it will create a database if no database exist on the path.
// generate databasePath programmatically
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
// your code here
}
post a comment if you need more code example on this
-(void)viewDidLoad
{
[super 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: #"contacts.sqlite"]];
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)
{
NSLog(#"if");
}
sqlite3_close(contactDB);
} else
{
NSLog(#"else");
}
}
[filemgr release];
}
-(IBAction)table
{
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.sqlite"]];
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 LIST (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"tables failed");
// status.text = #"Failed to create table";
}
sqlite3_close(contactDB);
}
else
{
NSLog(#"tables failed");
//status.text = #"Failed to open/create database";
}
}
[filemgr release];
}
import in .m file #import sqlite3.h and add framework in ur project libsqlite3.0.dylib
firstly create NSObject class and named it Database.
in .h class
#interface database : NSObject
{
NSString *databasePath;
NSString *databaseName;
sqlite3 *myDatabase;
NSArray *documentPaths;
NSString *documentsDir;
}
//---initial methods-------
-(void)createDatabaseIfNeeded;
//-----------------path find method---------------------//
-(void)pathFind;
//-----------------write value----------------------//
-(void)writeValueInSettings:(NSMutableArray *)arrayvalue;
//-------------------fetch value from setting table------------//
-(NSMutableArray *)fetchValue;
//-------------------update value---------------------//
-(void)updateSetting:(NSArray *)arr;
.m class write
-(id)init
{
if((self=[super init]))
{
[self createDatabaseIfNeeded];
}
return self;
}
//-----------create database if needed method--------------//
-(void)createDatabaseIfNeeded
{
[self pathFind];
BOOL success;
NSFileManager *filemgr = [NSFileManager defaultManager];
success=[filemgr fileExistsAtPath:databasePath];
if (success)return;
NSLog(#"not success");
//Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
// Copy the database from the package to the users filesystem
[filemgr copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
//----------------path find-----------------//
-(void)pathFind
{
databaseName = #"accDataBase.DB";
// Get the path to the documents directory and append the databaseName
documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
}
//------------------write value in setting----------------//
-(void)writeValueInSettings:(NSMutableArray *)arrayvalue
{
NSLog(#"%#",arrayvalue);
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
database *objectDatabase=[[database alloc]init];
NSString *stringvalue2=[objectDatabase countValue];
[objectDatabase release];
int intvalue1=[stringvalue2 intValue];
intvalue1=intvalue1+1;
NSLog(#"opened");
NSString *sql1;
sql1=[[NSString alloc] initWithFormat:#"insert into setting values('%i','%i','%i','%#','%i','%i','%#','%i','%i','%i','%i','%i','%i','%#');",intvalue1,
[[arrayvalue objectAtIndex:0] intValue],[[arrayvalue objectAtIndex:1] intValue],[arrayvalue objectAtIndex:2],[[arrayvalue objectAtIndex:3] intValue],[[arrayvalue objectAtIndex:4]intValue ],[arrayvalue objectAtIndex:5],[[arrayvalue objectAtIndex:6]intValue],[[arrayvalue objectAtIndex:7]intValue ],[[arrayvalue objectAtIndex:8] intValue],[[arrayvalue objectAtIndex:9] intValue],[[arrayvalue objectAtIndex:10]intValue ],[[arrayvalue objectAtIndex:11]intValue],[arrayvalue objectAtIndex:12]];
char *err1;
if (sqlite3_exec(myDatabase,[sql1 UTF8String],NULL,NULL,&err1)==SQLITE_OK)
{
NSLog(#"value inserted:");
}
[sql1 release];
sqlite3_close(myDatabase);
}
}
//------------fetch all value-------------//
-(NSMutableArray *)fetchValue
{
NSMutableArray *list=nil;
list=[[[NSMutableArray alloc]init] autorelease];
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
NSString *sql=[NSString stringWithFormat: #"select * from setting where primaryKey=1"];
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(myDatabase, [sql UTF8String], -1,&statement, NULL)==SQLITE_OK)
{
if(sqlite3_step(statement)==SQLITE_ROW)
{
for(int i=0;i<=13;i++)
{
char *pass=(char*)sqlite3_column_text(statement,i);
NSString *msg=[[NSString alloc]initWithUTF8String:pass];
[list addObject:msg];
[msg release];
}
}
sqlite3_finalize(statement);
}
sqlite3_close(myDatabase);
}
return list;
}
//----------------update setting table method---------------//
-(void)updateSetting:(NSArray *)arr
{
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
NSLog(#"opened");
sqlite3_stmt *compiledStmt;
// NSLog(#"%#",arr);
NSString *sqlStmt=[NSString stringWithFormat:#"UPDATE setting SET ragular=%i,cycle=%i, flow='%#', hour=%i,minute=%i,formate='%#' ,tenminute=%i ,thirtyminute=%i,sixtymin=%i, twentymin=%i, fourtyfivemin=%i ,other='%#',formatemessage ='%#' WHERE primaryKey=%i;",[[arr objectAtIndex:0]intValue],[[arr objectAtIndex:1]intValue],[arr objectAtIndex:2],[[arr objectAtIndex:3]intValue],[[arr objectAtIndex:4]intValue],[arr objectAtIndex:5],[[arr objectAtIndex:6]intValue],[[arr objectAtIndex:7]intValue],[[arr objectAtIndex:8]intValue],[[arr objectAtIndex:9]intValue],[[arr objectAtIndex:10]intValue],[arr objectAtIndex:11],[arr objectAtIndex:12],1];
// NSLog(#"%#",sqlStmt);
if(sqlite3_prepare_v2(myDatabase, [sqlStmt UTF8String],-1,&compiledStmt, NULL)==SQLITE_OK)
{
NSLog(#"updateding......cycle");
}
sqlite3_step(compiledStmt);
sqlite3_close(myDatabase);
}
}