How to update a table in SQLite database in objective C? - iphone

I created a table named "dept" in sqlite manually that has username (as Varchar) and Password (as Integer).
I used the following code to update a table
NSString *database2=[[NSBundle mainBundle]pathForResource:#"deptDatabase" ofType:#"sqlite"];
NSString *databasePath2=[NSString stringWithFormat:#"%#",database2];
const char *dbPath=[databasePath2 UTF8String];
if (sqlite3_open(dbPath, &dbHandler)==SQLITE_OK) {
NSLog(#"database Opened");
const char* updateQuery="update dept set password=1234 where username='suren'";
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(dbHandler, updateQuery, -1, &stmt, NULL)==SQLITE_OK) {
NSLog(#"Query Executed");
}
}
sqlite3_close(dbHandler);
but the table seems to be not updating.
Can anyone pls tell me how to update the table by altering the above code.
Thanks in advance

You can't not update fils in the mainBundle, these files are readonly.
To make changes to the database, you will have to copy it to the document directory.
And use the database in the document directory and not the one in the main bundle.
Only use the one in the main bundle as a payload file to be copied to the document directory if there is not file there.
Why do you create a new string here:
NSString *database2=[[NSBundle mainBundle]pathForResource:#"deptDatabase" ofType:#"sqlite"];
NSString *databasePath2=[NSString stringWithFormat:#"%#",database2];
The database2 is same as databasePath2. You are only using up memory here.

copy file from bundle to documents directory
NSString *databaseName = #"YOUR DB NAME WITH EXTENSION";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success=[fileManager fileExistsAtPath:databasePath];
if (!success) {
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
then u can work in the path databasePath (documents directory)
const char *dbPath=[databasePath UTF8String];
if (sqlite3_open(dbPath, &dbHandler)==SQLITE_OK) {
NSLog(#"database Opened");
const char* updateQuery="update dept set password=1234 where username='suren'";
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(dbHandler, updateQuery, -1, &stmt, NULL)==SQLITE_OK) {
NSLog(#"Query Executed");
}
}
sqlite3_close(dbHandler);
hope it helps.. happy coding :)

Related

iPhone - Trying to Copy sqlite Database to Documents Directory - copies blank version

I have an sqlite database called 'ProductDatabase.sql', which I have copied into my applications project directory:
/Users/jacknutkins/Documents/TabbedDietApp/TabbedDietApp/ProductDatabase.sql
In the applications app delegate class I have this piece of code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//Set-up some globals
m_DatabaseName = #"ProductDatabase.sql";
//Get the path to the documents directory and append the databaseName
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
m_DatabasePath = [documentsDirectory stringByAppendingPathComponent:#"ProductDatabase.sql"];
//Execute the "checkAndCreateDatabase" function
[self checkAndCreateDatabase];
//Query the databse for all animal records and construct the "animals" array
[self readProductsFromDatabase];
....
At this point:
m_DatabasePath = '/Users/jacknutkins/Library/Application Support/iPhone Simulator/5.0/Applications/6D5BBE3A-BC9A-4C44-B089-FABA27CFFF4B/Library/ProductDatabase.sql'
Here is the code for the other 2 methods:
- (void) checkAndCreateDatabase {
NSError * error;
//Check if the database has been saved to the users phone, if not then copy it over
BOOL l_Success;
//Create a file manager object, we will use this to check the status
//of the databse and to copy it over if required
NSFileManager *l_FileManager = [NSFileManager defaultManager];
//Check if the database has already been created in the users filesystem
l_Success = [l_FileManager fileExistsAtPath:m_DatabasePath];
//If the database already exists then return without doing anything
if(l_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 *l_DatabasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:m_DatabaseName];
//Copy the database from the package to the usrrs filesystem
[l_FileManager copyItemAtPath:l_DatabasePathFromApp toPath:m_DatabasePath error:&error];
}
If I perform some NSLogs here:
l_DatabasePathFromApp = /Users/jacknutkins/Library/Application Support/iPhone Simulator/5.0/Applications/6D5BBE3A-BC9A-4C44-B089-FABA27CFFF4B/TabbedDietApp.app/ProductDatabase.sql
and:
error = Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x6b6d060 {NSFilePath=/Users/jacknutkins/Library/Application Support/iPhone Simulator/5.0/Applications/6D5BBE3A-BC9A-4C44-B089-FABA27CFFF4B/TabbedDietApp.app/ProductDatabase.sql, NSUnderlyingError=0x6b6cfa0 "The operation couldn’t be completed. No such file or directory"}
I'm not sure what file it is it can't find here..
- (void) readProductsFromDatabase {
//Init the products array
m_Products = [[NSMutableArray alloc] init];
NSLog(#"%#", m_DatabasePath);
//Open the database from the users filessystem
if(sqlite3_open([m_DatabasePath UTF8String], &database) == SQLITE_OK) {
//Set-up the SQL statement and compile it for faster access
const char *sqlStatement = "select * from products";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
NSLog(#"Success..");
//Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
//Read the data from the results row
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aCategory = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aCalories = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSString *aFat = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
NSString *aSaturates = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)];
NSString *aSugar = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)];
NSString *aFibre = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)];
NSString *aSalt = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 8)];
NSString *aImageURL = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 9)];
NSLog(#"Delegate");
NSString *aNote = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 10)];
NSUInteger myInt = sqlite3_column_int(compiledStatement, 11);
NSString *aServes = [NSString stringWithFormat:#"%d", myInt];
//Create a new animal object with the data from the database
Product *l_Product = [[Product alloc] initWithName:aName category:aCategory calories:aCalories fat:aFat saturates:aSaturates sugar:aSugar fibre:aFibre salt:aSalt imageURL:aImageURL note:aNote serves:aServes];
//Add the animal object to the animals array
[m_Products addObject:l_Product];
}
}
//Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
database is declared in the .h file as follows:
//Setup the database object
sqlite3 *database;
In the above method, the line:
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
does not evaluate to SQLITE_OK, because the database I try to copy to the documents directory is blank.
I have tried cleaning and building, deleting the blank copy of the database and re-running etc but it continues to copy a blank database every time.
I've googled this several times and I've tried everything I can find with no success..
Any help would be hugely appreciated.
Jack
EDIT
If I perform 'select * from products' from the terminal window on the database in the project directory I return the expected results.
I had forgotten to include the database file in the target membership by clicking on the check box in the file inspector tab.

how to create a sqlite

how to create a sqlite file when the application starts (didFinishLaunchingWithOptions) the test if it already or not exsist otherwise create the file sqlite
Like this... the sqlPath variable is the path to the pre-made sql database on your ressource
- (void) checkAndCreateSQL
{
if (![[NSFileManager defaultManager] fileExistsAtPath:[documentPath stringByAppendingString:#"/database.sql"]]) {
[[NSFileManager defaultManager] createFileAtPath:[documentPath stringByAppendingString:#"/database.sql"]
contents:[NSData dataWithContentsOfFile:sqlPath]
attributes:nil];
}
}
EDIT 1:
You can create the database on your mac using this command line :
sqlite3 database.sql < DATABASE_CREATION.txt
in the DATABASE_CREATION.txt something like this :
CREATE TABLE IF NOT EXISTS `group` (
`id` integer PRIMARY KEY,
`name` text,
`position` integer
);
Then put directly the database.sql file into your project resource. (like an image)
You'd probably want to use the default Core Data libraries instead of manually creating and handling a single sqlite file. Please check the official Apple Core Data Programming Guide. It will automatically handle the creation and update of the inner database in the app.
sqlite3 *reference2Database() {
if (_database == nil) {
// First, test for existence.
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"my.sqlite"];
if ([fileManager fileExistsAtPath:writableDBPath] == NO) {
// Database file doesnt exists. Copy the database at writable path (documents directory).
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"my.sqlite"];
[fileManager removeItemAtPath:writableDBPath error:nil];
BOOL databaseCopied = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!databaseCopied) {
// Handle the error...
}
}else {
// Open the database. The database was prepared outside the application.
if (sqlite3_open([writableDBPath UTF8String], &_database) != SQLITE_OK) {
// Even though the open failed, call close to properly clean up resources.
sqlite3_close(_database);
_database = nil;
// Additional error handling, as appropriate...
}
}
}
return _database;
}
// Sample usage.
-(void) someDatabaseFunction {
sqlite3 *database = reference2Database();
// Do something with "database"...
}
// Close the database. This should be called when the application terminates.
void closeDatabase() {
if (_database == nil) return;
// Close the database.
if (sqlite3_close(_database) != SQLITE_OK) {
// Handle the error...
}
_database = nil;
}
NOTE: At the top of the file, you should have: static sqlite3 *_database = nil;
I use Matteo Bertozzi's SQLite Wrapper to create my sqlite database with the following code:
-(void)checkDatabase
{
if([[NSFileManager defaultManager] fileExistsAtPath:DBPATH] == NO)
{
sqlite = [[Sqlite alloc] init];
if (![sqlite open:DBPATH]) return;
[sqlite executeNonQuery:#"DROP TABLE yourtable"];
[sqlite executeNonQuery:#"CREATE TABLE yourtable (record1 TEXT NOT NULL,
record2 TEXT NOT NULL,
record3 TEXT NOT NULL,
record4 TEXT NOT NULL);"];
NSArray *results = [sqlite executeQuery:#"SELECT * FROM yourtable;"];
for (NSDictionary *dictionary in results) {
for (NSString *key in [dictionary keyEnumerator])
NSLog(#" - %# %#", key, [dictionary objectForKey:key]);
}
[results release];
[sqlite release];
}
}

Not able to insert data in to sqlite table

I am new to iphone development,i was trying to insert the data in a sqlite table .but data is not inserted in the table.there was no error on the console.
NSString *string1=#"Test";
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"TestData" ofType:#"sqlite"];
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK)
{
sqlite3_stmt *compiledStatement=nil;
char * sql = "insert into Test (title,summary,question,choice,answer) values (?,?,?,?,?)";
if (sqlite3_prepare_v2(database, sql, -1, &compiledStatement, NULL) == SQLITE_OK)
{
{
sqlite3_bind_text(compiledStatement, 1, [string1 UTF8String], -1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 2,[string1 UTF8String] , -1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 3, [string1 UTF8String], -1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 4, [string1 UTF8String], -1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 5, [string1 UTF8String], -1,SQLITE_TRANSIENT);
if(sqlite3_step(compiledStatement) != SQLITE_DONE )
{
NSLog( #"Error: %s", sqlite3_errmsg(database) );
}
else {
NSLog( #"Insert into row id = %d", sqlite3_last_insert_rowid(database));
}
}
As your database in resource bundle you are trying to modify and update it. The better approach would be place your database first time in documents directory of sandbox and then perform operation on that database.
Here is the method using which you can move your database to documents directory of your application's sandbox. This method should be called only once while using database operation.(because only first time we need to place it at that location, other times we just need to access it).
Code :
// Name : configureDatabase:
// Description : Method configures the database with new name.
// Arguements : NSString : Databse file name
// Retrun : None
-(void) configureDatabase:(NSString *)newDatabaseName
{
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [[documentsDir stringByAppendingPathComponent:newDatabaseName]retain];
// Execute the "checkAndCreateDatabase" function
[self checkAndCreateDatabase:databasePath];
}
// Name : checkAndCreateDatabase:
// Description : Method checks and creates the database file at the given path if its not present.
// Arguements : NSString : file path.
// Retrun : None.
-(void) checkAndCreateDatabase:(NSString *)dbPath
{
// 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:dbPath];
// 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] pathForResource:#"TestData" ofType:#"sqlite"];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:dbPath error:nil];
}
Also note that if we are using database so it is good practice to locate it first in some directory from where user can take backup. Documents directory of sandbox is one of these backup ready directory.
Thanks,

iPHONE SDK- sqlite , how do i do an insert statement

i have a database that is in the documents directorys of the
Application/iPhoneSimulator/3.2/Applications/etc/Documents
I have this code under my method
databaseName = #"database.sql";
NSArray *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory.NSUserDomainMask,YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
How do i do an insert with a variable/ array .
Something like
"INSERT INTO TABLE (COLUMN) VALUES ('%#'),[appDelegate.variable objectAtIndex:0];
I insist you to go through this question.
First of all copy the database from main bundle to your application's document dir.
You can follow below code to implement it.
NSString *databaseFile=[[NSBundle mainBundle] pathForResource:kDataBaseName ofType:kDataBaseExt];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString *dbPath=[basePath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#",kDataBaseName,kDataBaseExt]];
NSFileManager *fm=[NSFileManager defaultManager];
if(![fm fileExistsAtPath:dbPath]){
[fm copyItemAtPath:databaseFile toPath:dbPath error:nil];
}
[fm release];
self.dataBasePath=dbPath;
I am supplying you directly my project code. Please add comment if any doubts.
I have added comments for the explanation.
// function with multiple arguments which is going to be used for inserting into table.
+(void)insertBuilding:(NSString*)BName streetNo:(NSInteger)streetNo streetName:(NSString*)streetName streetDir:(NSString*)streetDir muni:(NSString*)muni province:(NSString*)province bAccess:(NSString*)bAccess bType:(NSString*)bType amnity:(NSString*)amnity latitude:(NSString*)latitude longitude:(NSString*)longitude imageName:(NSString*)imageName {
// application delegate where I have saved my database path.
BuildingLocatorAppDelegate *x=(BuildingLocatorAppDelegate *)[[UIApplication sharedApplication]delegate];
sqlite3 *database; // database pointer
// verifying if database successfully opened from path or not.
// you must open database for executing insert query
// i have supplied database path in argument
// opened database address will be assigned to database pointer.
if(sqlite3_open([[x dataBasePath] UTF8String],&database) == SQLITE_OK) {
// creating a simple insert query string with arguments.
NSString *str=[NSString stringWithFormat:#"insert into buildingDtl(b_name,streetNo,streetName,streetDir,muni,province,b_access,b_type,aminity,latitude,longitude,b_image) values('%#',%i,'%#','%#','%#','%#','%#','%#','%#','%#','%#','%#')",BName,streetNo,streetName,streetDir,muni,province,bAccess,bType,amnity,latitude,longitude,imageName];
// converting query to UTF8string.
const char *sqlStmt=[str UTF8String];
sqlite3_stmt *cmp_sqlStmt;
// preparing for execution of statement.
if(sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt, NULL)==SQLITE_OK) {
int returnValue = sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt, NULL);
((returnValue==SQLITE_OK) ? NSLog(#"Success") : NSLog(#"UnSuccess") );
// if NSLog -> unsuccess - that means - there is some problem with insert query.
sqlite3_step(cmp_sqlStmt);
}
sqlite3_finalize(cmp_sqlStmt);
}
sqlite3_close(database);
// please don't forget to close database.
}
+(NSString *)stringWithFormat:(NSString *)format parameters:...];
NSString sql = [NSString stringWithFormat:#"INSERT INTO table VALUES('%#')", #"Hello, world!"];
sqlite3_....
Use either prepared statements in combination with the bind_*() functions (e.g. bind_text()) or the mprintf() function to insert strings, see this question for details.
To get a raw C-string you can pass to these functions use -UTF8String or -cStringUsingEncoding: on a NSString.

sqlite error :/* SQL error or missing database */

I have a project in which I stored sqlite database file "data.sqlite3" to
'Group'&files'-'resource'
Below are my viewcontroller source codes
//-myviewcontroller.h
#import "sqlite3.h"
#define kFilename #"data.sqlite3"
//myviewcontroller.m
-(NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
-(void)f
{
if (sqlite3_open([[self dataFilePath] UTF8String],&database)!=SQLITE_OK)
//dataFilePath returns
///Users/interdev/Library/Application Support/iPhone Simulator/User/Applications/095C6E05-4EAE-4817-883E-A72E39D439E0/Documents/data.sqlite3
{
sqlite3_close(database);
NSAssert(0,#"Failed to open database");//no problem
}
NSString *query = #"SELECT * FROM table1 ORDER BY ROW";//table1 is table name
sqlite3_stmt *statement;
NSInteger v=sqlite3_prepare_v2( database, [query UTF8String],
-1, &statement, nil);
NSString *zs= [NSString stringWithFormat:#"%d",v];
NSLog(#" The buttontitile is %# ",zs);
if ( v == SQLITE_OK) { // ...
}
I checked value of v in log, it always is 1
#define SQLITE_ERROR 1 /* SQL error or missing database */
I do not know why this happened.
It looks like your code is looking for your database in the 'Documents' folder of your application.
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
Thus, if the data.sqlite3 file is in your Resources folder, the applicaiton is not going to find the database. It's probably best to create and store the sqlitedatabase in the 'Documents' folder of the applicaiton. E.g /Users/interdev/Library/Application Support/iPhone Simulator/User/Applications/095C6E05-4EAE-4817-883E-A72E39D439E0/Documents/data.sqlite3