Auto incrementing 'id' value when inserting into sqlite

淺唱寂寞╮ 提交于 2019-12-12 06:49:55

问题


I'm trying to figure out how to get id value into database in an auto increment way, i.e it sets it self automatically depending on what entry is.

here is how my DatabaseHandler code looks at the moments (only important bits)

    // Adding new appointment
    void addAppointment(Appointment appointment) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ID, appointment.getId()); // Appointment ID
        values.put(KEY_TITLE, appointment.getTitle()); // Appointment Title
        values.put(KEY_DETAILS, appointment.getDetails()); // Appointment Details
        values.put(KEY_DATE, appointment.getDate()); // Appointment Date
        values.put(KEY_TIME, appointment.getTime()); // Appointment Time

        // Inserting Row
        db.insert(TABLE_APPOINTMENTS, null, values);
        db.close(); // Closing database connection
    }

as you can see I use constructor without id in it, this always returns 0 for id, thus returns an error as id must be PRIMARY KEY must be unique

How do I make it auto increment?


回答1:


Remove the

values.put(KEY_ID, appointment.getId()); // Appointment ID

When the PRIMARY KEY is not specified, a value is automatically generated.



来源:https://stackoverflow.com/questions/22441287/auto-incrementing-id-value-when-inserting-into-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!