尝试(失败)从iphone在sqlite中插入数据
您好,我正在开发一个使用sqlitedb的应用程序。 我读了一些例子,并尝试创建我的应用程序。 我要插入的表有3列。 ID整型主键自动递增、名称文本、实时持续时间、实时 我根据阅读的示例编写以下代码。 但我总是看到未能添加记录。 附言: 我测试了db创建,没问题。 我在另一个应用程序上使用了它,这是可以的。但是这里不行尝试(失败)从iphone在sqlite中插入数据,iphone,ios,objective-c,sqlite,insert,Iphone,Ios,Objective C,Sqlite,Insert,您好,我正在开发一个使用sqlitedb的应用程序。 我读了一些例子,并尝试创建我的应用程序。 我要插入的表有3列。 ID整型主键自动递增、名称文本、实时持续时间、实时 我根据阅读的示例编写以下代码。 但我总是看到未能添加记录。 附言: 我测试了db创建,没问题。 我在另一个应用程序上使用了它,这是可以的。但是这里不行 NSTimeInterval endTime = [[NSDate date] timeIntervalSinceReferenceDate]; dou
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);
}
这是因为您正在将数据直接写入resources文件夹中的
数据库
。它不可写入。首先,您需要复制文档目录中的数据库
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");
}
从代码中删除bind语句并将其更改为
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应用程序中管理数据感兴趣,我建议您完成以下教程,因为这是一个非常好的介绍:
本教程使用SQLite处理iPhone应用程序中的数据选择、更新、插入和删除。感谢您的回复和建议链接。我应该去看看。但是我用了这个教程,它很管用,但是我想当我改变数据类型时,我遇到了错误,我用了这个教程,没关系,但是当我尝试另一个数据类型时,我遇到了错误