简体   繁体   中英

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

}

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;
}
    NSString *updateSQL = [NSString stringWithFormat: @"update CONTACTS set address='%@',phone='%@',imageUrl='%@' WHERE name='%@'",daddress.text,dphone.text,durl.text,dname.text];

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM