Inserting a data into SQLite (using FMDB) doesn't work on device?

£可爱£侵袭症+ 提交于 2020-01-16 10:56:03

问题


I am a newbie here. I am not able to insert any data into my SQLite database when running on my device. I am using the below piece of code to connect SQLite. It works perfect in my simulator but doesn't work on my iPad device. Can anyone help please? Thank you.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"DADatabase1.sqlite"];
NSLog(@"%@", writableDBPath);

FMDatabase* db = [FMDatabase databaseWithPath:writableDBPath];

/*if ([fileManager fileExistsAtPath:writableDBPath] == NO) {
    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"DADatabase1.sqlite" ofType:@"sqlite"];
    [fileManager copyItemAtPath:resourcePath toPath:writableDBPath error:nil];
}*/
[db open];
[db traceExecution];
[db beginTransaction];
BOOL success = [db executeUpdate:[NSString stringWithFormat:@"insert into PatientDetails (patAge) values (?)",patAge.text]];
if(!success)
{
    NSLog(@"Query not success!");
}
else {
    NSLog(@"Query success!");
}
//NSString *query = [NSString stringWithFormat:];
[db commit];
[db close];

回答1:


Did you put your Database with your Tables in your Projects resources folder? You have to copy your database file to your Apps Document folder.

+ (BOOL)initDB {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"sqlite.db"]; 

NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: path])
{
    NSString *bundle =  [[ NSBundle mainBundle] pathForResource:@"sqlite" ofType:@"db"];
    [fileManager copyItemAtPath:bundle toPath:path error:nil];
    return YES;
}
    return NO;
}



回答2:


The sample code provided doesn't have a CREATE TABLE statement. The INSERT has nowhere to insert to. Did you create the table manually (using the sqlite3 command line tool) while you were developing in the simulator?




回答3:


NOTE that:

File names in simulator is not case sensitive, but in device is case sensitive. Make sure your file name is exactly same.



来源:https://stackoverflow.com/questions/11824013/inserting-a-data-into-sqlite-using-fmdb-doesnt-work-on-device

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!