写数据到源码的Xcode(Writing data to sqlite xCode)

2019-09-19 02:32发布

首先我是从西班牙关于我的语法非常抱歉。 我写了一些数据,以一个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]错误:列密钥不唯一

所以,我的代码应该没问题,但是当我打开数据库的完全空的,什么想法?

Answer 1:

你在你的主束的SQLITE数据库文件。 在主束的所有文件是只读的。 您需要将数据库复制到文件夹。

尝试了这一点(从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]);
}
}


文章来源: Writing data to sqlite xCode
标签: ios xcode sqlite