2013-08-13 4 views
0

Я хочу обновить записи из нескольких текстовых элементов в подробном viewcontroller, но когда я cliCk на кнопке обновления, его не удается обновить базу данных. PLS предложить мне.Как я могу обновить базу данных sqlite

-(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) 
     { 
      [email protected]"updated successfully"; 
     } 
     else 
     { 
      dstatuslabel.text = @"Failed to update contact"; 
     } 

     sqlite3_finalize(statement); 
     sqlite3_close(Information); 
    } 

} 
+2

Распечатать [сообщение об ошибке] (http://stackoverflow.com/questions/6171056/sqlite3-error-ios) первый. Без сообщения об ошибке мы не сможем вам помочь. – DarkDust

+0

Что вы уже сделали, чтобы попытаться разрешить это? Например, какой код ошибки выполняет 'sqlite3_step', если вы не SQLITE_DONE? –

+0

нет никакого сообщения об ошибке, но база данных не обновляется, выполняется еще одна статута «Не удалось обновить контакт с базой данных» –

ответ

0
NSString *updateSQL = [NSString stringWithFormat: @"update CONTACTS set address='%@',phone='%@',imageUrl='%@' WHERE name='%@'",daddress.text,dphone.text,durl.text,dname.text]; 
+0

NSString * updateSQL = [NSString stringWithFormat: @ "update КОНТАКТЫ set address = '% @', phone = '% @', imageUrl = '% @' WHERE name = '% @'", daddress.text, dphone.text , durl.text, dname.text]; здесь, на месте имени, я хочу использовать первичный ключ, так как я могу это сделать ?? –

+1

Не обновлять первичный ключ. Это может вызвать множество проблем, связанных с сохранением ваших данных, если у вас есть другие таблицы, ссылающиеся на него. В идеале, если вы хотите изменить уникальное поле, создайте новое поле. – Rajneesh071

0

В моем методе я использую следующим образом свою работу:

-(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; 

} 
+0

PLS обзор мой вопрос, это не моя проблема. я уже определил метод для обновленных PLS, предложите мне, где ошибка? спасибо –

+1

попытайтесь распечатать сообщение об ошибке .. Какое сообщение об ошибке вы получаете? –

+0

@DivyaBhalodiya. Вы сообщите OP, чтобы распечатать сообщение об ошибке, и все же вы не делаете этого в своем собственном коде. Кажется странным. – trojanfoe

0

Добавьте БД SQLite, как и любой другой файл в вашем пакета приложения

Скопируйте его в каталог документов с помощью кода и использования это (Метод: checkAndCreateDatabase). Целью этого является то, что обновление содержания в SQLite можно в каталоге Documents только

-(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; 
} 
+0

NSString * updateSQL = [NSString stringWithFormat: @ "update КОНТАКТЫ set address = '% @', phone = '% @', imageUrl = '% @' WHERE name = '% @'", daddress.text, dphone.text , durl.text, dname.text]; здесь, на месте имени, я хочу использовать первичный ключ, так как я могу это сделать ?? –

0

Попробуйте это ... Он должен работать ...

1) Пожалуйста, убедитесь, вы копируете дб от своего расслоения каталога документов перед обновлением БД ...

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) Шаг 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"); 
    } 
} 
+0

NSString * updateSQL = [NSString stringWithFormat: @ "update КОНТАКТЫ set address = '% @', phone = '% @', imageUrl = '% @' WHERE name = '% @'", daddress.text, dphone.text , durl.text, dname.text]; здесь, на месте имени, я хочу использовать первичный ключ, так как я могу это сделать ?? –

Смежные вопросы