2013-07-10 2 views
1

У меня есть база данных с таблицей, у меня есть база данных отдельно в файле sqlite, который я создал с помощью терминала, и представление, которое позволяет мне создавать мои данные, а затем вводить их в базу данных хотя, когда я нажимаю «Сохранить», похоже, он не сохраняется.База данных SQLite не сохраняет данные

Вот мои SQLite скрипты:

-(void) addPatientToDatabase:(Patient *)newPatient { 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsPath = [paths objectAtIndex:0]; 
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"cities.sqlite"]; 

    sqlite3 *database; 

    if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) { 
     const char *sqlStatement = "insert into patients (firstName, surname, dob, homeNumber, mobileNumber, email, address, image) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; 
     sqlite3_stmt *compiledStatement; 
     if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { 
      sqlite3_bind_text(compiledStatement, 1, [newPatient.patientName UTF8String], -1, SQLITE_TRANSIENT); 
      sqlite3_bind_text(compiledStatement, 2, [newPatient.patientSurname UTF8String], -1, SQLITE_TRANSIENT); 
      sqlite3_bind_text(compiledStatement, 3, [newPatient.patientDoB UTF8String], -1, SQLITE_TRANSIENT); 
      sqlite3_bind_text(compiledStatement, 4, [newPatient.patientHomeNumber UTF8String], -1, SQLITE_TRANSIENT); 
      sqlite3_bind_text(compiledStatement, 5, [newPatient.patientMobileNumber UTF8String], -1, SQLITE_TRANSIENT); 
      sqlite3_bind_text(compiledStatement, 6, [newPatient.patientEmail UTF8String], -1, SQLITE_TRANSIENT); 
      sqlite3_bind_text(compiledStatement, 7, [newPatient.patientAddress UTF8String], -1, SQLITE_TRANSIENT); 
      NSData *dataForPicture = UIImagePNGRepresentation(newPatient.patientPicture); 
      sqlite3_bind_blob(compiledStatement, 8, [dataForPicture bytes], [dataForPicture length], SQLITE_TRANSIENT); 
     } 
     if(sqlite3_step(compiledStatement) == SQLITE_DONE) { 
      sqlite3_finalize(compiledStatement); 
     } 
    } 
    sqlite3_close(database); 
} 

и:

Patient *newPatient = [[Patient alloc] init]; 
    newPatient.patientName = firstnameEntry.text; 
    newPatient.patientSurname = surnameEntry.text; 
    newPatient.patientDoB = dobEntry.text; 
    newPatient.patientHomeNumber = homeNumberEntry.text; 
    newPatient.patientMobileNumber = mobileNumberEntry.text; 
    newPatient.patientEmail = emailAddressEntry.text; 
    newPatient.patientAddress = addressEntry.text; 
    newPatient.patientPicture = patientPicture; 
    [patients addObject:newPatient]; 
    [self addPatientToDatabase:newPatient]; 

и:

-(NSString *)copyDatabaseToDocuments { 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString * documentsPath = [paths objectAtIndex:0]; 
    NSString *filepath = [documentsPath stringByAppendingPathComponent:@"patients.sqlite"]; 

    if (![fileManager fileExistsAtPath:filepath]) { 
     NSString *bundlePath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"patients.sqlite"]; 
     [fileManager copyItemAtPath:bundlePath toPath:filepath error:nil]; 
    } 
    return filepath; 
} 

-(void) readPatientsFromDatabaseWithPath:(NSString *)filePath { 
    sqlite3 *database; 

    if (sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) { 
     const char *sqlStateMent = "select * from patients"; 
     sqlite3_stmt *compiledStatement; 
     if (sqlite3_prepare(database, sqlStateMent, -1, &compiledStatement, NULL) == SQLITE_OK) { 
      while (sqlite3_step(compiledStatement) == SQLITE_ROW) { 
       NSString *firstName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]; 
       NSString *surname = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)]; 
       NSString *dob = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)]; 
       NSString *homeNumber = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)]; 
       NSString *mobileNumber = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)]; 
       NSString *email = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)]; 
       NSString *address = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)]; 
       NSData *patientData = [[NSData alloc] initWithBytes:sqlite3_column_blob(compiledStatement, 8) length:sqlite3_column_bytes(compiledStatement, 8)]; 
       UIImage *patientImage = [UIImage imageWithData:patientData]; 
       Patient *newPatient = [[Patient alloc] init]; 
       newPatient.patientName = firstName; 
       newPatient.patientSurname = surname; 
       newPatient.patientDoB = dob; 
       newPatient.patientHomeNumber = homeNumber; 
       newPatient.patientMobileNumber = mobileNumber; 
       newPatient.patientEmail = email; 
       newPatient.patientAddress = address; 
       newPatient.patientPicture = (UIImage *)patientImage; 
       [self.patients addObject:newPatient]; 
      } 
     } 
     sqlite3_finalize(compiledStatement); 
    } 
    sqlite3_close(database); 
} 

Это не похоже, как if(sqlite3_step(compiledStatement) == SQLITE_DONE) {

Я попытался положитьbreakpoint в середине чтения, и он также не достиг точки останова.

Извините, что есть так много кода и не много текста.

Укажите, хотите ли вы больше кода или деталей.

Заранее спасибо

+0

Вы получаете какие-либо сообщения об ошибках назад –

+0

Нет, которая является одним из самых странных вещей об этом –

+0

есть у отлаживать код выше ... – Anjaneyulu

ответ

0

Вы initialsing базы данных и создания в на локальной файловой системе, прежде чем использовать его первым.

Если нет, то вы можете использовать следующий код, чтобы сделать это:

-(void) checkAndCreateDatabase 
{ 

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDir = [documentPaths objectAtIndex:0]; 
    NSString *databaseName = @"mydatabase.db"; 
    NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseName]; 
// 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]; 


} 
+0

У меня есть база данных отдельно в файле sqlite, который я сделал с помощью терминала –

+0

@ user2568107. Вы отправляете какие-либо данные в базу данных? Если вы можете получить данные из базы данных? –

+0

У меня нет данных в базе данных, когда приложение загружается –

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