1

首先,我来自西班牙,对我的语法感到抱歉。我正在将一些数据写入 sqlite 数据库,这是我的代码:

@try {

    NSFileManager *fileMgr=[NSFileManager defaultManager];

    NSString *dbPath=[[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:@"capturas.sqlite"];
    BOOL succes=[fileMgr fileExistsAtPath:dbPath];
    if(!succes)
    {
        NSLog(@"Cannot locate database '%@'.",dbPath);
    }
    if (!(sqlite3_open([dbPath UTF8String], &dbcapturas)==SQLITE_OK)) {
        NSLog(@"An error has occured: %@",sqlite3_errmsg(dbcapturas));
    }

    //sqlite3_stmt *sqlStatement;
    NSString *asd=numero.text;
    NSString *insertStatement=[NSString stringWithFormat:@"INSERT INTO captura(key,tecnico, fecha,provincia,municipio,latitud,longitud,altura,familia,especie,numero,comentario)Values(\"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\")",asd,tecnico,fechaHora,tecnico,municipio,latitud,longitud,altura,tecnico,animal,asd,coment];
    char *error;
    if((sqlite3_exec(dbcapturas, [insertStatement UTF8String], NULL, NULL, &error))==SQLITE_OK)
    {
        NSLog(@"Person inserted.");
    }
    else
    {
        NSLog(@"Error: %s", error);
    }
} @catch (NSException *exception) { 
    NSLog(@"fail"); 
}
@finally {

}

第一次单击保存按钮时,我得到:

2012-07-04 12:17:45.644 adasdasd[1783:f803] 插入的人。

我第二次得到:

2012-07-04 12:29:18.959 adasdasd[1840:f803] 错误:列键不唯一

所以我的代码应该没问题,但是当我打开数据库时它完全是空的,知道吗?

4

1 回答 1

2

你的主包中有你的 SQLITE db 文件。主包中的所有文件都是只读的。您需要将 db 复制到 Documents 文件夹。

试试这个(来自http://www.iphonedevsdk.com/forum/iphone-sdk-development/17262-sqlite-database-works-fine-on-simulator-but-is-readonly-on-device.html):

- (void)createEditableCopyOfDatabaseIfNeeded
{
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@\"database_name.sql\"];
success = [fileManager fileExistsAtPath:writableDBPath];
// NSLog(@\"path : %@\", writableDBPath);
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@\"database_name.sql\"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success)
{
NSAssert1(0, @\"Failed to create writable database file with message '%@'.\", [error localizedDescription]);
}
}
于 2012-08-21T13:38:13.710 回答