How to capture the Primary Key Duplicated error in Android (java) with SQLServer?

0

Is it possible to know that the error that occurs when inserting a record is due to a duplicate key error? I have a user registry in which the user is the primary key and I have it in try catch but when the user already exists it jumps to catch Now what I want is to tell the user that the registration could not be completed because the user already exists, could before making the insert verify if the user exists but I wonder if the catch could do that function here the example code:

try{
    String sql = "INSERT INTO usuarios values('usuario','password')";
        st.execute(sql);
        connect.close();
}catch(Exception e){
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}

In the Toast I would like to tell the user that there was a duplicity error, but the Exception can jump through several situations.

    
asked by Igmer Rodriguez 28.11.2018 в 15:51
source

1 answer

1

In Java and therefore in Android you have the exception SQLException , which captures all the exceptions related to SQL statements, either a failure that does not find the table, until the field already exists and control your error. To execute some code, simply put it in the catch block.

try{
    String sql = "INSERT INTO usuarios values('usuario','password')";
        st.execute(sql);
        connect.close();
}catch(SQLException e){
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
//Intentar la conexión o insertar otro dato
}
    
answered by 29.11.2018 в 12:00