1. 程式人生 > >Android Sqlite insert後得到自增主鍵

Android Sqlite insert後得到自增主鍵

問題

主鍵是自增的,插入之後,物件的id並沒有被賦值,搞不到物件的id。

解決

剛開始根據插入內容查詢到該記錄從而獲取id,但是檢視原始碼發現了更好的辦法。

    /**
     * Convenience method for inserting a row into the database.
     *
     * @param table the table to insert the row into
     * @param nullColumnHack optional; may be <code>null</code>.
     *            SQL doesn't allow inserting a completely empty row without
     *            naming at least one column name.  If your provided <code>values</code> is
     *            empty, no column names are known and an empty row can't be inserted.
     *            If not set to null, the <code>nullColumnHack</code> parameter
     *            provides the name of nullable column name to explicitly insert a NULL into
     *            in the case where your <code>values</code> is empty.
     * @param
values this map contains the initial column values for the * row. The keys should be the column names and the values the * column values * @return the row ID of the newly inserted row, or -1 if an error occurred */
public long insert(String table, String nullColumnHack, ContentValues values) { try
{ return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE); } catch (SQLException e) { Log.e(TAG, "Error inserting " + values, e); return -1; } }
@return the row ID of the newly inserted row, or -1 if an error occurred

已經說得很明白了,insert方法的返回值就是新插入的記錄的id,如果返回值是-1說明沒插入成功。