错误 SQLite异常: 外键不匹配



我想在表中插入一个寄存器,结构如下:

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上重现相同的错误,但是在该平台上,它不知何故没有导致任何错误。

我的语法有什么问题?

从文档中:

如果数据库模式包含需要查看多个表定义才能识别的外键错误,则在创建表时不会检测到这些错误。相反,此类错误会阻止应用程序准备 SQL 语句,这些语句以使用外键的方式修改子表或父表的内容。

如果出现以下情况,可能会报告外键 DML 错误:

  • 父表不存在,或者
  • 外键约束中指定的父键列不存在,或者
  • 父键列 在外键约束中命名的不是主键 父表,并且不受使用 创建表中指定的排序规则序列,或
  • 子表 引用父项的主键而不指定 主键列和主键列数 父项与子键列数不匹配。

但是,浏览一下您的代码,似乎大多数代码都被遵循了。您确定在创建过程中没有错误,例如,无法首先创建父表?(因为您在插入过程中稍后会收到错误,所以我想知道您是否在该过程的早期错过了错误。

而且,您确定这些是您正在创建的表吗?因为你有一个if not exists条款;也许存在具有不同架构的旧版本的表,而您当前上面(我认为)正确的代码不是现在实际运行的代码?使用工具查看或额外设备/模拟器中的原始 SQL Lite 数据库,以查看其中的架构是否与当前在上面提供的命令匹配。

文档说:

如果出现以下情况,可能会报告外键 DML 错误:[...]

  • 外键约束中指定的父键列不存在

在这种情况下,父键列确实不存在:

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

最新更新