获取SQLite数据库的下一个AUTO_INCREMENT值

时间:2011-08-05 01:23:27

标签: android sqlite auto-increment

使用Android API中的典型SQLiteDatabase对象,如何在不影响值本身的情况下获取特定列的下一个AUTO_INCREMENT值(即id)。有没有办法呢?或者我应该执行什么查询来获得该结果。请记住,SQLiteDatabase.query()返回一个Cursor对象,所以如果我只是想从中获取一个值,我不太确定如何直接处理它。

7 个答案:

答案 0 :(得分:13)

你是对的。第一个答案(仍在下面)仅适用于没有AUTOINCREMENT的id。使用AUTOINCREMENT时,值将存储在单独的表中并用于增量。以下是查找值的示例:

public void printAutoIncrements(){
    String query = "SELECT * FROM SQLITE_SEQUENCE";
    Cursor cursor = mDb.rawQuery(query, null);
    if (cursor.moveToFirst()){
        do{
            System.out.println("tableName: " +cursor.getString(cursor.getColumnIndex("name")));
            System.out.println("autoInc: " + cursor.getString(cursor.getColumnIndex("seq")));

        }while (cursor.moveToNext());
    }

    cursor.close(); 

}

请参阅:http://www.sqlite.org/autoinc.html

第一回答:

您可以查询_id列的最大值,例如:

String query = "SELECT MAX(id) AS max_id FROM mytable";
Cursor cursor = db.rawQuery(query, null);

int id = 0;     
if (cursor.moveToFirst())
{
    do
    {           
        id = cursor.getInt(0);                  
    } while(cursor.moveToNext());           
}
return id;

这适用于尚未指定为“INTEGER PRIMARY KEY AUTOINCREMENT”的行ID(所有表都有行id列)。

答案 1 :(得分:5)

关于SQLITE_SEQUENCE表的重要说明。

文档说

  

只要创建包含AUTOINCREMENT列的普通表,就会自动创建并初始化SQLITE_SEQUENCE表。

因此创建了SQLITE_SEQUENCE表,但不是与包含AUTOINCREMENT列的表关联的行。该行是使用第一个插入查询创建的(“seq”值为1)。

这意味着在查找特定表的下一个自动增量值之前,必须至少执行一次插入操作。例如,可以在创建表之后,执行插入和删除虚拟行来完成它。

答案 2 :(得分:5)

这是使用SQLITE

获取自动增量PRIMARY KEY的最后一个ID的最佳方法

String query = "select seq from sqlite_sequence WHERE name = 'Table_Name'"

答案 3 :(得分:2)

以下是我用于获取特定表的下一个 AUTOINCREMENT 值的信息:

/**
 * Query sqlite_sequence table and search for the AUTOINCREMENT value for <code>tableName</code>
 * @param tableName The table name with which the AUTOINCREMENT value is associated.
 *
 * @return The next AUTOINCREMENT value for <code>tableName</code>
 * If an INSERT call was not previously executed on <code>tableName</code>, the value 1 will
 * be returned. Otherwise, the returned value will be the next AUTOINCREMENT.
 */
private long getNextAutoIncrement(String tableName) {
    /*
     * From the docs:
     * SQLite keeps track of the largest ROWID using an internal table named "sqlite_sequence".
     * The sqlite_sequence table is created and initialized automatically
     * whenever a normal table that contains an AUTOINCREMENT column is created.
     */
    String sqliteSequenceTableName = "sqlite_sequence";
    /*
     * Relevant columns to retrieve from <code>sqliteSequenceTableName</code>
     */
    String[] columns = {"seq"};
    String selection = "name=?";
    String[] selectionArgs = { tableName };

    Cursor cursor = mWritableDB.query(sqliteSequenceTableName, 
            columns, selection, selectionArgs, null, null, null);

    long autoIncrement = 0;

    if (cursor.moveToFirst()) {
        int indexSeq = cursor.getColumnIndex(columns[0]);
        autoIncrement = cursor.getLong(indexSeq);
    }

    cursor.close();

    return autoIncrement + 1;
}

答案 4 :(得分:1)

在您使用的SQLiteOpenHelper中,启动一个事务。插入一些数据然后回滚。

这样,你就可以获得下一行id,如下所示:

public long nextId() {
    long rowId = -1;

    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();
    try {
        ContentValues values = new ContentValues();
        // fill values ...

        // insert a valid row into your table
        rowId = db.insert(TABLE_NAME, null, values);

        // NOTE: we don't call  db.setTransactionSuccessful()
        // so as to rollback and cancel the last changes
    } finally {
        db.endTransaction();
    }
    return rowId;
}

答案 5 :(得分:1)

It's work.

public static long getNextId(SQLiteDatabase db, String tableName) {
    Cursor c = null;
    long seq = 0;
    try {
        String sql = "select seq from sqlite_sequence where name=?";
        c = db.rawQuery(sql, new String[] {tableName});
        if (c.moveToFirst()) {
            seq = c.getLong(0);
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return seq + 1;
}

答案 6 :(得分:0)

您可以使用i方法
Cursor c = db.rawQuery("Select * From mSignUp", null); String mail = null; try { while (c.moveToNext()) { mail = c.getString(0); String pas = c.getString(1); Toast.makeText(getApplicationContext(), "Name = " + mail + " Pass = " + pas, Toast.LENGTH_SHORT).show(); } }catch (CursorIndexOutOfBoundsException e){ Log.e("OutOfBound", Log.getStackTraceString(e)); } finally { c.close(); } 这里是id列的索引

<div id="mainHead">
  <div class="ui pointing menu fluid four item inverted " id="menu">
    <a href="index.php" class="item">
      <i class="home icon"></i> Home
    </a>
    <a href="about.php" class="item">
      <i class="user icon"></i> About
    </a>
    <a href="portfolio.php" class="item">
      <i class="archive icon"></i> Portfolio
    </a>
    <a href="contact.php" class="item">
      <i class="mail icon"></i> Contact
    </a>
  </div>
  <div class="ui labeled icon button black">
    <i class="icon list layout"></i>
    Menu
  </div>
</div>