Hossam Oukli
Hossam Oukli

Reputation: 1296

Can't insert a row in a table with a foreign key

I'm having troubles with inserting a row in my database Table 'Article' which contains a foreign key that is linked to an autoincrement primaryKey in table Categorie.

Here are my tables:

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+"));";

Once this line of code is executed :

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

i keep getting this error while inserting a line into 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

the value 9 already exists in my table Categorie enter image description here

here my uploadProduct method:

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;
            }

Upvotes: 1

Views: 234

Answers (1)

Tom Studee
Tom Studee

Reputation: 10452

Is the foreign key value you are referencing already inserted into table B? If not, you need to do so before inserting into table A.

Upvotes: 1

Related Questions