vpgr
vpgr

Reputation: 5

Inserting to SQLite database in android and return an autoincremented value

Im trying to work with android and SQLite database. Im not sure how to add data to this row of the table and get the gameid column which autoincrements returned back in the same method. (this is my first post please excuse my posting errors)

public static final String GAME_COLUMNS = " ( GAME_ID INTEGER PRIMARY KEY AUTOINCREMENT, ADMIN_ID TEXT, SCORE1 INTEGER DEFAULT 0, SCORE2 INTEGER DEFAULT 0 );";


public int createGame(String email){
    if(email!=null){
        SQLiteDatabase test = this.getWritableDatabase();
        test.execSQL("INSERT INTO "+ GAME_TABLE + " VALUES(NULL, '"+ email + "',NULL, NULL);");
        int gameID = test.executeQuery("select last_insert_id() from "+GAME_TABLE);

        return gameID;
    }

}

Upvotes: 0

Views: 1315

Answers (1)

John Joe
John Joe

Reputation: 12803

You don't need to use select last_insert_id().

public int createGame(String email) {
    int result = -1;
    if (email!=null) {
        SQLiteDatabase test = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(EMAIL, email);                                                                                                                                
        result = database.insert(GAME_TABLE, null, values); // this will return the last id you inserted
    }
    return result;
}

Upvotes: 2

Related Questions