SQLite check if data already exists

1

Hello

I have an application where when logging in if you have a connection to the internet it should bring the data from the web service and insert it into the bank. That's good then, but my doubt is as follows:

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

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

Below is my code for insertion into 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";

}
    
asked by anonymous 08.09.2016 / 14:31

1 answer

2

Instead of using

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

use

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

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

    
08.09.2016 / 15:24