sukh punjabi
sukh punjabi

Reputation: 69

Android SQlite, how do I check if the value in database already exists?

public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE " + DATABASE_TABLE_COURSES + " ("
                + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
                + KEY_COURSE_ID + " TEXT NOT NULL, "
                + KEY_COURSE_TITLE + " TEXT NOT NULL, "
                + KEY_COURSE_CNUMBER + " TEXT NOT NULL, "
                + KEY_COURSE_SUBJECT + " TEXT NOT NULL, " 
                + KEY_COURSE_DAYS + " TEXT NOT NULL, "
                + KEY_COURSE_START_TIME + " TEXT NOT NULL, "
                + KEY_COURSE_END_TIME + " TEXT NOT NULL, "
                + KEY_COURSE_PROFESSOR + " TEXT NOT NULL, "
                + KEY_COURSE_BUILDING + " TEXT NOT NULL, " 
                + KEY_COURSE_ROOM_NUMBER + " TEXT NOT NULL);");

I want to check that if the course_id already exists in the table, then don't make another entry. Thanks

Upvotes: 3

Views: 3900

Answers (1)

Ashwin
Ashwin

Reputation: 13517

To check if a field exists or not in general :

 Cursor cur1=db.query("database_table_courses", "course_id=id_u_wanttocheck", null, null, null, null, null);
      cur1.moveToLast();
      int count1=cur1.getCount();
      if(count1==0)
      {
          //course id not present

      }
      else
      {
        //course id present
      }


Or if you want the course_id to be never repeated in the table, you can set that as the primary key and remove the primary key tag from row_no. This way you can simply insert a new row. If the course_id is alreday present it willnot insert and throw an exception - SQLException, you can catch it and do what ever you want.

Upvotes: 4

Related Questions