插入数据库时​​出现SQlite错误

时间:2012-11-09 20:08:20

标签: database xcode xcode4 sqlite

我花了几天时间来修复这段代码而且我放弃了! 我正在做的是从用户那里获取输入并将其插入数据库,如果他按下“保存”按钮。 当我运行此代码并按下“保存”按钮后。 1-我无法退出View(到另一个选项卡)。 2-插入没有应用!!

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"CAMAClientDB2.sqlite"];
    sqlite3 *database;


    //Copy the database from the package to the usrrs filesystem
    if (sqlite3_open([dbPath UTF8String], &database)== SQLITE_OK) {//start if 
        NSLog(@"dataBaseOpen");
        const char *sqlStatement = "insert into Location (Latitude,Longitude,LocationName,Tag) VALUES (?,?,?,?)";
        // 
        sqlite3_stmt *compileStatement;

        if (sqlite3_prepare_v2(database, sqlStatement, -1, &compileStatement, NULL) == SQLITE_OK) { // start if 2
            if(SQLITE_DONE!=sqlite3_step(compileStatement))
            {
            sqlite3_bind_double(compileStatement, 1, [latitudeTextField.text doubleValue]);

            sqlite3_bind_double(compileStatement, 2, [longitudeTextField.text doubleValue]);

            sqlite3_bind_text( compileStatement, 3, [lName.text UTF8String], -1, SQLITE_TRANSIENT);

            sqlite3_bind_text(compileStatement, 4, [myText.text UTF8String] ,-1, SQLITE_TRANSIENT);
             NSLog( @" successfully done" );
            if(sqlite3_step(compileStatement) != SQLITE_DONE ) {
                NSLog( @" not done" );
            }  
            }

        }
    }

我输入appDelegate代码来处理文件管理器:

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);     NSString * documentsDir = [paths objectAtIndex:0];

NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"CAMAClientDB2.sqlite"];


NSFileManager *fileManager = [NSFileManager defaultManager];

BOOL success = [fileManager fileExistsAtPath:dbPath];

if (success) {

    NSLog(@"we have the database");

} else {

    NSLog(@"we have no database");

    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"CAMAClientDB2.sqlite"];


    BOOL moved = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:nil];

    if (moved) {
        NSLog(@"database copied");
    }



}

我有没有想念!问题是什么 !!

1 个答案:

答案 0 :(得分:0)

对于你的#2问题: 1.你有一个额外的sqlite_step调用。你的顺序应该是:

    sqlite3_prepare_v2()
            sqlite_bind_....
            sqlite_bind_....
            for as many bind's as you need, and then
            sqlite_step()
  1. 如果sqlite_step仍然失败,请检查返回代码并在文档中查找指导

  2. 如果您的MacOS应用程序是沙箱,则无法使用。目前无法自行更新sqlite数据库。您必须获得sqlite文件所在目录的用户写入权限,或者您必须将其放入包中(这实际上是相同的)