我有一个table tableGrupo(Groups),它具有来自其他表tableMaquinas(Machines)的外键。当我在表tableGrupo(Groups)中插入数据时,Android Studio告诉我外键字段不能为空,因为它是外键。如何在Android中的SQLite中插入foreignKey值?
为了让插入接受并将正确的外键ID传递给我应该赋予什么值?
这是我的代码:
//Table1
db.execSQL("CREATE TABLE "+ tableGrupo +" ("+
idGrupo +" INTEGER PRIMARY KEY AUTOINCREMENT, "+
nomeGrupo +" TEXT)");
//Table2
db.execSQL("CREATE TABLE "+ tableMaquinas +" ("+
idMaquina +" INTEGER PRIMARY KEY AUTOINCREMENT, "
+ nomeMaquina + " text not null, "
+ imagemMaquina + " BLOB, "
+ id_grupo + " integer, "
+ " FOREIGN KEY ("+id_grupo+") REFERENCES "+tableGrupo+"("+idGrupo+"))");
**This is the code where I make the insertion in the database**
public void addMachine(String name, byte[] image) throws SQLiteException {
ContentValues values = new ContentValues();
values.put(nomeMaquina,name);
values.put(imagemMaquina,image);
//here i have to put a value for the foreignkey
this.getWritableDatabase().insert(tableMaquinas,null,values);
}
与关系数据库中的想法是,它可以访问该数据,其中第外键所指向。所以FOREIGN KEY指向的ID应该已经存在。如果它不是这样的数据库没有意义。如果存在,您的密钥不为空。所以,也许有一点误会......你必须有一个有效的外键... – Opiatefuchs
但是,当我添加一些东西时,外键的值是空的,android studio会一直在窃听我! – jose
你永远不会将值赋给id_grupo,因此,sqlite无法将你的Maquina关联到Grupo(顺便说一句,强烈建议在所有表中标准化变量命名 - id_grupo或idGrupo)。 Android Studio不是代理,它只是一个在物理或虚拟设备上运行的IDE(模拟器不是Android工作室本身),而是一个IDE(ambiente interacttivo de desenvolvimento)代码,适用于Android studio ,即使您可能正在使用AVD/Android监视器窗口看到它,也是发生错误的位置。 –