我关于stackoverflow的第一个问题,我真的希望你们能帮助我。
我一直在努力让准备好的语句在目标 C 中运行,到目前为止一切都很好。但是现在,当我尝试添加曲目时,我的数据库中不断出现“约束失败”。
我已经删除了数据库并再次创建了它,但错误仍然存在。此外,我一直在研究重复键,但我没有看到我在任何地方添加重复键。位置表添加得很好,并且它的构建方式相同。
我的数据库:
CREATE TABLE locations
(LocationID INTEGER PRIMARY KEY AUTOINCREMENT,
TimestampGPS DATE NOT NULL,
Longitude REAL NOT NULL,
Latitude REAL NOT NULL,
Altitude REAL NOT NULL,
Accuracy REAL NOT NULL,
Bearing REAL NOT NULL,
Speed REAL NOT NULL,
TimestampDevice DATE NOT NULL);
CREATE TABLE tracks
(TrackID INTEGER PRIMARY KEY AUTOINCREMENT,
Title VARCHAR,
Description VARCHAR,
StartTrackDeviceTime DATE NOT NULL,
EndTrackDeviceTime DATE NOT NULL);
CREATE TABLE track_locations
(TrackID INTEGER NOT NULL REFERENCES tracks(TrackID),
LocationID INTEGER NOT NULL REFERENCES locations(LocationID),
PRIMARY KEY (TrackID, LocationID));
我添加曲目的代码。(我有代码来添加一个类似的位置,并且工作得很好)
const char *sqlTrack = "INSERT INTO tracks(Title, Description, StartTrackDeviceTime, EndTrackDeviceTime) VALUES(?, ?, ?, ?)";
if(sqlite3_prepare_v2(db.dataBase, sqlTrack, -1, &addTrackStatement, NULL) != SQLITE_OK) {
NSLog(@"Error: %s", sqlite3_errmsg(db.dataBase));
}
sqlite3_bind_text(addTrackStatement, 1, [track.title UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addTrackStatement, 2, [track.description UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addLocationStatement, 3, [[dateFormatter stringFromDate:track.startTime] UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addTrackStatement, 4, [[dateFormatter stringFromDate:track.endTime] UTF8String], -1, SQLITE_TRANSIENT);
NSLog(@"Going to execute the statement");
if(SQLITE_DONE != sqlite3_step(addTrackStatement)) {
NSLog(@"First step failed");
NSLog(@"Error: %s", sqlite3_errmsg(db.dataBase));
return NO;
}
else {
long insertedTrack = sqlite3_last_insert_rowid(db.dataBase);
NSLog(@"Inserted id on TRACK: %ld", insertedTrack);
//HERE I ALSO ADD LOCATIONS
sqlite3_clear_bindings(addTrackStatement);
sqlite3_reset(addTrackStatement);
}