Sqlite check if data already exists

Asked

Viewed 110 times

1

Hello

I have an application where when logging in if you have internet connection it should bring the data from the web service and enter in the bank. So far so good, but my doubt is as follows:

When logging in and receiving user data through a web service query, I want to check if this user already exists in my table and do the following procedures:

If it exists, update it. If it does not exist, insert it.

Below follows my entry code in the database.

  private SQLiteDatabase db;
private CriaBanco criaBanco;

public ProfessorDAO(Context context) {criaBanco = new CriaBanco(context);}

public String insereProfessor(Professor professor) {
    ContentValues valores;
    long resultado = 1;

    db = criaBanco.getWritableDatabase();
    valores = new ContentValues();
    valores.put("CODPROF", professor.getCodProfessor());
    valores.put("NOME", professor.getNomeProfessor());
    valores.put("USUARIO", professor.getUsuario());
    valores.put("SENHA", professor.getSenha());

    resultado = db.insertOrThrow("PROFESSOR", null, valores);
    db.close();

    if (resultado == -1)
        return "Erro de registro";
    else
        return "Registro Inserido com sucesso";

}
  • You can check if the bank is null when it is empty is returned as null

  • OK, but what if it is data but these data are not up to date

1 answer

2

Instead of using

resultado = db.insertOrThrow("PROFESSOR", null, valores);

use

resultado = db.repalace("PROFESSOR", null, valores);

replace create a new registration or update an existing one with the same primary key(1).

(1) "values" must contain the column(s) (s) referring(s) to the primary key of the table PROFESSOR

Browser other questions tagged

You are not signed in. Login or sign up in order to post.