我不断地出错,遗憾的是我看不出我做错了什么。我想要一个插入tripname
、timestamp
、lat
、longi
、accuracy
和speed
的语句。我已经制作了数据库,但我无法编写成功的SQL语句,请帮助
这是我的代码:
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
NSString *databaseDir;
NSArray *dirPath;
//get the documents path
dirPath= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
databaseDir =[dirPath objectAtIndex:0];
databasePath=[[NSString alloc]initWithString: [databaseDir stringByAppendingPathComponent:
@"deathTrail.db" ]];
sqlite3_stmt *statement;
const char *dbpath=[databasePath UTF8String];
if (sqlite3_open(dbpath, &deathTrail)==SQLITE_OK){
NSString *sql_stmt1=[[NSString alloc] initWithFormat:@"INSERT VALUES INTO LOCATION_POINTS (LATITUDE, LONGITUDE) VALUES ("%d", "%d")", newLocation.coordinate.latitude, newLocation.coordinate.longitude];
const char *insertstmt=[sql_stmt1 UTF8String];
sqlite3_prepare_v2(deathTrail, insertstmt, -1, &statement,NULL);
if(sqlite3_step(statement)==SQLITE_DONE) {
status.text=@"it worked";
} else {
status.text=@"it failed";
}
sqlite3_finalize(statement);
sqlite3_close(deathTrail);
}
}
-
您也应该检查
sqlite3_prepare_v2
命令的结果。 -
如果它或
sqlite3_step
失败,您应该检查sqlite3_errmsg
的结果,以便了解失败的原因(在这种情况下,因为上面的代码没有明显的问题,我认为这是因为表不存在)。 -
通常,如果您在尝试打开数据库时知道该数据库应该存在,则应该使用
sqlite_open_v2
(例如sqlite3_open(dbpath, &deathTrail, SQLITE_OPEN_READWRITE, NULL)
),这样它就不会为您创建空白数据库。或者,如果您希望它创建数据库,那么继续使用sqlite3_open
,但如果表还不存在,请确保您正在执行适当的SQLCREATE TABLE
语句。 -
如果你认为它错误地为你创建了一个空白数据库,不要忘记重置你的模拟器,或者删除并重新安装程序,以确保任何空白数据库都会被删除。
-
如果您计划使用捆绑包中的数据库进行读写,请确保以编程方式将数据库从捆绑包复制到documents文件夹。
这个问题解决了吗?
如果没有,还有一件事需要检查。如果您在应用程序的任何时候执行SELECT语句,却忘记包含sqlite3_finalize(语句);那么insert语句将不起作用。注销sql错误消息将显示"数据已锁定"。您仍然可以执行更多的SELECT语句,但任何地方只缺少一个finalize语句,INSERTS将被破坏。