开发者

SQLiteConstraintException with Android

I'm creating a dataBase to insert a *unique patient *(no more than one), so I just created a database that doesn't autoincrement its id like this:

CREATE TABLE IF NOT EXISTS PACIENTE(idPaciente INTEGER PRIMARY KEY,  nombre VARCHAR(100) NOT NULL, apellidos VARCHAR(100), email VARCHAR(100), genero CHAR,  edad INTEGER NOT NULL, peso INTEGER, kMedico INTEGER, pkHistorial INTEGER,  pkConfProg INTEGER, altura INTEGER,  FOREIGN KEY (pkMedico) REFERENCES MEDICO(idMedico),  FOREIGN KEY (pkHistorial) REFERENCES HISTORIAL(idHistorial),  FOREIGn KEY (pkConfProg) REFERENCES CONFPROGRAMA(idConf));

As you can see, the way to add a patient here is tell the database the idPaciente explicitly.

So I used this code to insert a patient:

public long addPaciente(BDPaciente pac)
{
ContentValues cv = new ContentValues();
cv.put("idPaciente", 1);
cv.put("nombre", pac.getNombre());
cv.put("edad", 26);

try
{
    db.insert("PACIENTE", null, cv);
    return -1;
}
catch (SQLiteConstraintException e)
{
    return -100;
}

}

As you can see, what I'm trying to do is insert a patient, and then, if it is inser开发者_如何学JAVAted before, catch the Exception and throw it to my parent Window. The thing is that, the exception is thrown, but not catched. And the program says:

Error inserting nombre=blabla edad=25 idPaciente=1 android.database.SQLiteConstraintException: error code 19: constraint failed

I know that it's something about the duplication on the primary key, but I wanna do so!


Flo, thanky you for your answer, but yes, I created the table, but what I didn't post, is that I have a method for erasing all databases and then creating them again whenever I press a button like this:

    db.execSQL(DROP_TABLE_HISTORIAL);
    db.execSQL(DROP_TABLE_MEDICO);
    db.execSQL(DROP_TABLE_CONF);
    db.execSQL(DROP_TABLE_PACIENTE);

So yes, I'm sure. But what Sarmand answered works for me, so thank you for your help :-)

Sorry, but I can't vote... Don't have enough points >_<


If you want to duplicate primary key then dont declare it as primary key. Do it like this

CREATE TABLE IF NOT EXISTS PACIENTE(idPaciente INTEGER , ....);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜