0

您好,我正在开发一个使用 sqlitedb 的应用程序。我阅读了一些示例并尝试创建我的应用程序。我要插入的表有 3 列。ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, DURATION REAL, TIME REAL 我根据我读过的例子写了下面的代码。但我总是看到添加记录失败。PS:我测试了数据库创建,没问题。我用这个教程 在另一个应用程序上没问题。但这里不起作用

        NSTimeInterval endTime = [[NSDate date] timeIntervalSinceReferenceDate];

    double elapsedTime = endTime-startcache;

    NSString *my=[NSString stringWithFormat:@"%f",elapsedTime];
    TextField1.text=my;

    // saving in database
   NSString * durationstring=[NSString stringWithFormat:@"%f",elapsedTime];
  NSString *   timestring=[NSString stringWithFormat:@"%f",endTime];

    sqlite3_stmt    *statement;
    const char *dbpath = [_databasePath UTF8String];

    if (sqlite3_open(dbpath, &_activityDB) == SQLITE_OK)
    {

        NSString *insertSQL = [NSString stringWithFormat:
                               @"INSERT INTO ACTIVITYTABLE (name, duration,time ) VALUES (\"%@\", \"%@\", \"%@\")",
                               activityname, durationstring,timestring];

        const char *insert_stmt = [insertSQL UTF8String];
        sqlite3_prepare_v2(_activityDB, insert_stmt,
                           -1, &statement, NULL);
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            self.status.text = @"record added";


        } else {
            self.status.text = @"Failed to add record";
        }
        sqlite3_finalize(statement);
        sqlite3_close(_activityDB);
    }
4

1 回答 1

1

这是因为您直接将数据写入database资源文件夹。它是不可写的,您首先需要将 in 复制databasedocument directory.

NSError *err=nil;
    NSFileManager *fm=[NSFileManager defaultManager];

    NSArray *arrPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, -1);
    NSString *path=[arrPaths objectAtIndex:0];
   NSString path2= [path stringByAppendingPathComponent:@"ProductDatabase.sql"];


   if(![fm fileExistsAtPath:path2])
    {

      bool success=[fm copyItemAtPath:databasePath toPath:path2 error:&err];
        if(success)
            NSLog(@"file copied successfully");
       else
           NSLog(@"file not copied");

    }

并从代码中删除绑定语句并将其更改为

if(sqlite3_prepare_v2(database, insert_stmt, -1, &statement, nil)== SQLITE_OK)
        {


        if(sqlite3_step(statement)==SQLITE_DONE) 
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Product Added" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];    
            [alert show];

        }
        else 
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Product Not Added" message:@"An error has occured" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];   
            [alert show];
            alert=nil;
        }   
}

如果你真的对学习如何使用 SQLite 管理 iPhone 应用程序中的数据感兴趣,我建议你完成以下教程,因为它是一个很好的介绍:

http://www.icodeblog.com/2008/08/19/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-1/

本教程使用 SQLite 在 iPhone 应用程序中处理选择、更新、插入和删除数据。

于 2013-07-22T16:57:48.190 回答