无法在具有外键的表中插入行

时间:2013-06-10 00:52:57

标签: sqlite foreign-keys

我在我的数据库表'Article'中插入一行时遇到麻烦,该表包含链接到表Categorie中的自动增量primaryKey的外键。

以下是我的表格:

static String CREATE_CATEGORIE = "create table "
    + TABLE_CATEGORIE + "(" 
    + COLUMN_ID_CATEGORIE + " Integer primary key autoincrement, "           
    + COLUMN_NOMCAT + " text not null, " 
    + COLUMN_CHILDS + " text, " 
    + COLUMN_ROOT + " boolean not null, "
    + COLUMN_CAT_STRUCT + " text not null);";

static String CREATE_UPLOAD_2 = "create table "
    + TABLE_UPLOAD + "(" + COLUMN_ID
    + " Integer primary key autoincrement, " 
    + COLUMN_NAME + " text not null, " 
    + COLUMN_DESCRIPTION + " text not null, " 
    + COLUMN_PRIX + " text not null, "
    + COLUMN_STATUS + " integer not null, "
    + COLUMN_SPECEFIC + " text not null, "
    + COLUMN_ID_CATEGORIE + "Integer not null, "
    +"FOREIGN KEY ("+COLUMN_ID_CATEGORIE+") REFERENCES "+TABLE_CATEGORIE+" ("+COLUMN_ID_CATEGORIE+"));";

执行此行代码后

long idArticle= database.uploadProduct(Name, Description, Prix, specefic, idCategorie, 2);
//idCategorie = 9

我在向TABLE_UPLOAD插入一行时一直收到此错误:

    06-10 00:41:13.922: E/Database(7332): Error inserting _id=9 prix=Hossam 
    specific=champ1|hhh;champ2|hhh;champ3|hhh; status=2 description=Hossam nom=Hossam

   06-10 00:41:13.922: E/Database(7332): android.database.sqlite.SQLiteConstraintException:
   error code 19: constraint failed

我的表分类中已存在值9 enter image description here

这是我的uploadProduct方法:

public long uploadProduct(String Name,String Description,String Prix,Map<String,String> speceficInfo,int idCat,int status) 
            {
                ContentValues values = new ContentValues();
                values.put(MySqlHelper.COLUMN_NAME, Name);
                values.put(MySqlHelper.COLUMN_DESCRIPTION, Description);
                values.put(MySqlHelper.COLUMN_PRIX, Prix);
                values.put(MySqlHelper.COLUMN_STATUS, status);
                values.put(MySqlHelper.COLUMN_SPECEFIC,mapToString(speceficInfo));
                values.put(MySqlHelper.COLUMN_ID_CATEGORIE, idCat);
                long id=database.insert(MySqlHelper.TABLE_UPLOAD, null,values);
                return id;
            }

1 个答案:

答案 0 :(得分:1)

您引用的外键值是否已插入表B?如果没有,您需要在插入表A之前这样做。