我在 vs2012 中使用 c 接口实现 SQLite。
我有三张桌子,其中两张是父母,它们没有通过任何键链接在一起。第三个是一个孩子,它应该有来自两个父表的两个外键。我尝试了以下但它没有工作给我以下错误:
foreign key contraints failed
这是我的实现:第一个父表:
CREATE TABLE Persons (
ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
Name CHAR NULL ,
Age INT NULL
);
第二个父表:
CREATE TABLE Jobs (
Job_ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
Description CHAR NULL ,
Country CHAR
);
子表
CREATE TABLE Persons_Jobs (
Title CHAR NULL,
country CHAR NULL,
ID INT ,
Job_ID INT ,
FOREIGN KEY (ID) REFERENCES Persons(ID) ,
FOREIGN KEY (Job_ID) REFERENCES Jobs(Job_ID)
);
注意我的表创建成功,前两张表的数据也插入成功。
更新 2:
插入语句:
void db_prepareInsertSql(sqlite3 *db){
sqlite3_int64 rowPersonID,rowJobID;
int i =0;
char *sql;
char str[100];
do{
i = i+1;
sprintf_s(str, "INSERT INTO Persons VALUES(NULL,'liena',%d);",i);
sql = str;
db_execute_sql(db,sql);
fprintf(stdout,"Persons insertion");
rowPersonID = sqlite3_last_insert_rowid(db);
sprintf_s(str, "INSERT INTO Jobs VALUES(NULL,'Doc','SDN');");
sql = str;
db_execute_sql(db,sql);
fprintf(stdout,"Jobs insertion");
rowJobID = sqlite3_last_insert_rowid(db);
\\the error occurs here
sprintf_s(str, "INSERT INTO Persons_Jobs VALUES('A','krt',%d,%d);",rowPersonID,rowJobID);
sql = str;
db_execute_sql(db,sql);
fprintf(stdout,"Persons_Jobs insertion");
}
while(i!=10);
}
表创建:
void db_prepareCreateTablesSql(sqlite3 *db){
char *sql;
char str[500];
sprintf_s(str, "PRAGMA foreign_keys = ON;");
sql = str;
db_execute_sql(db,sql);
fprintf(stdout,"Enable foriegn-keys feature");
sprintf_s(str, "CREATE TABLE IF NOT EXISTS Persons("
"ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
"Name CHAR NULL , "
"Age INT NULL ); ");
sql = str;
db_execute_sql(db,sql);
fprintf(stdout,"table Persons");
sprintf_s(str, "CREATE TABLE IF NOT EXISTS Jobs("
"Job_ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
"Description CHAR NULL , "
"Country CHAR )");
sql = str;
db_execute_sql(db,sql);
fprintf(stdout,"table Jobs");
sprintf_s(str, "CREATE TABLE IF NOT EXISTS Persons_Jobs("
"Title CHAR NULL , "
"country CHAR NULL , "
"ID INT , "
"Job_ID INT , "
"FOREIGN KEY (ID) REFERENCES Persons(ID),"
"FOREIGN KEY (Job_ID) REFERENCES Jobs(Job_ID)) ;");
sql = str;
db_execute_sql(db,sql);
fprintf(stdout,"table Persons_Jobs");
db_prepareInsertSql(db);
}
当我调试时,我发现了这个:
所以,我的问题出在子表中,如何从两个不同的父表中指定两个外键?