0

我要插入一個寄存器到一個表,結構如下:錯誤SQLiteException:外鍵不匹配

db=this.openOrCreateDatabase("calificaciones.db", MODE_PRIVATE, null); 
db.execSQL("PRAGMA foreign_keys=ON"); 
db.execSQL("create table if not exists usuarios (idusuario integer primary key autoincrement, nusuario text, contrasena text, correo text);"); 
db.execSQL("create table if not exists alumnos (idalumno integer primary key, apellidos text, nalumno text, especialidad text, grado text, grupo text);"); 
db.execSQL("create table if not exists materias (idmateria integer primary key, nmateria text,"+" docente text, horas integer);"); 
db.execSQL("create table if not exists calificacion (idcalif integer primary key autoincrement, idalumno integer, idmateria integer, idusuario integer, calificacion integer, parcial integer, foreign key(idalumno) references alumnos(idalumno), foreign key(idmateria) references materias(idmateria), foreign key(idusuario) references alumnos(idusuario));"); 

但是,在插入一個寄存器到表「Calificacion」的那一刻起,它給了我以下錯誤消息:

android.database.sqlite.SQLiteException: foreign key mismatch - "calificacion" referencing "alumnos" (code 1): , while compiling: insert into calificacion (idalumno, idmateria, idusuario, calificacion, parcial) values (15330050790409,42069,1,10,3);

它發生即使其它表的寄存器與我試圖插入到「Calificaciones」數據匹配。我試圖在SQL Fiddle上重現相同的錯誤,使用完全相同的查詢,但在該平臺中,它不會導致任何錯誤。

我的語法有什麼問題?

回答

0

docs

如果數據庫架構包含了需要尋找多個表的定義,以確定外鍵的錯誤,然後創建表時沒有檢測到這些錯誤。相反,此類錯誤會阻止應用程序準備使用外鍵修改子表或父表內容的SQL語句。

...

外鍵DML錯誤可能會報告,如果:

  • 父表不存在,或
  • 外鍵約束命名的父鍵的列別存在或
  • 在外鍵約束中指定的父鍵列 不是 父表的主鍵,並且不受使用的唯一約束在CREATE TABLE中指定排序序列,或
  • 子表,而無需指定 主鍵列,並在 父主鍵列的數目不匹配子鍵的數量的父的 引用的主鍵列。

然而,在你的代碼一眼,它看起來像大部分都是遵循。你確定在創建過程中沒有錯誤,例如,父表不能在第一時間創建? (因爲在插入過程中稍後會出現錯誤,所以我想知道是否在此過程中錯過了錯誤。)

而且,您確定這些是您創建的表嗎?因爲你有一個if not exists子句;也許老版本的表格有不同的架構,你現在的上面(我認爲)正確的代碼不是現在正在運行的?使用工具從設備/仿真器中查看或附加原始SQL Lite數據庫,以查看其中的架構是否與您當前正在提供的命令相匹配。

0

documentation說:

外鍵DML錯誤,如果可能會報告:[...]不存在

外鍵約束命名
  • 父鍵列

在這種情況下,父鍵列確實不存在:

... foreign key(idusuario) references alumnos(idusuario) 
             ▔▔▔▔▔▔▔ ▔▔▔▔▔▔▔▔▔