限制SQLite表具有特定的行数

时间:2016-12-30 04:35:03

标签: android android-sqlite

我有Sqlite Handler来保存和获取包含一些数据的行。我想要的是仅在任何给定时刻将行数限制为10。假设已经添加了10行并且我要保存另一行,它应该删除最先输入的最旧行,然后插入最新的条目。我搜索了它,我找到的唯一答案是创建一个触发器。但是没有解释如何在SQLite中执行此操作。有没有更好的方法呢?

public class SQLiteHandler extends SQLiteOpenHelper {

    private static final String TAG = "sammy_";

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "android_api";

    // Profile Settings table name
    private static final String TABLE_ITEM = "item";

    // Profile Settings information names
    private static final String KEY_ID = "id";
    private static final String KEY_TYPE = "type";
    private static final String KEY_TITLE = "title";
    private static final String KEY_SUBTITLE = "subtitle";
    private static final String KEY_APIID = "apiid";



    public SQLiteHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {

        String CREATE_PROF_TABLE = "CREATE TABLE " + TABLE_ITEM + "("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_TYPE+" TEXT, "+KEY_TITLE+" TEXT, "+KEY_SUBTITLE+" TEXT, "+KEY_APIID+" TEXT" + ")";

        db.execSQL(CREATE_PROF_TABLE);

        System.out.println("sammy_Database tables created");
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEM);

        // Create tables again
        onCreate(db);
    }


    /**
     * Storing Prof_settings details in database
     * */
    public void addContents(String type, String title, String subtitle, String apiid){

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_TYPE, type);
        values.put(KEY_TITLE, title);
        values.put(KEY_SUBTITLE, subtitle);
        values.put(KEY_APIID, apiid);

        long id = db.insert(TABLE_ITEM, null, values); // insert to 1st row
        db.close(); // Closing database connection

        //Log.d(TAG, "New profile settings inserted into sqlite: " + id);
        System.out.println("sammy_New content inserted into sqlite: "+id);

    }




    /**
     * Getting data from database
     * */
    public ArrayList<HashMap<String, String>> getAllContents()
    {
        ArrayList<HashMap<String, String>> array_list = new ArrayList<HashMap<String, String>>();

        SQLiteDatabase db = this.getReadableDatabase();
        //Cursor res = db.rawQuery("SELECT * " + " FROM " + TABLE_PROF + " GROUP BY " + KEY_NAME + " ORDER BY " + KEY_MOBILE + " COLLATE NOCASE;", null);
        String selectQuery = "SELECT  * FROM " + TABLE_ITEM;
        Cursor res = db.rawQuery(selectQuery, null);
        res.moveToFirst();

        while (res.isAfterLast() == false)
        {
            HashMap<String, String> hashmap= new HashMap<String, String>();
            hashmap.put("type", res.getString(res.getColumnIndex(KEY_TYPE)));
            hashmap.put("title", res.getString(res.getColumnIndex(KEY_TITLE)));
            hashmap.put("subtitle", res.getString(res.getColumnIndex(KEY_SUBTITLE)));
            hashmap.put("apiid", res.getString(res.getColumnIndex(KEY_APIID)));

            array_list.add(hashmap);
            res.moveToNext();
        }
        return array_list;
    }

    /**
     * Re create database Delete all tables and create them again
     * */
    public void deleteContents() {
        SQLiteDatabase db = this.getWritableDatabase();
        // Delete All Rows
        db.delete(TABLE_ITEM, null, null);
        db.close();
        System.out.println("sammy_Deleted all contents from sqlite");
        //Log.d(TAG, "Deleted all profile info from sqlite");
    }

}

4 个答案:

答案 0 :(得分:0)

我建议您在插入新记录时不要尝试清理数据库。相反,只需为每条记录存储一个时间戳,当您需要最新的10条时,只需使用:

ORDER BY timestamp DESC LIMIT 10

跟踪应用Java代码中最近10个条目的一个选项是使用LinkedHashMap,可配置为仅保留最近的10个条目。

答案 1 :(得分:0)

@Sam,

Dude假设您在表中只需要10条记录,您可以做的是在添加新记录时如果等于10,则可以删除第一条记录(旧记录),具体取决于您的主键中的主键i想一想id

所以创建一个返回计数的函数

public int getProfilesCount() {
    String countQuery = "SELECT  * FROM " + TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int cnt = cursor.getCount();
    cursor.close();
    return cnt;
}

由于您未使用任何时间戳字段,因此您根据id确定最早的记录,因为它是primary key

所以在你的addContents函数中添加我在评论中给出的代码

/**
 * Storing Prof_settings details in database
 * */
public void addContents(String type, String title, String subtitle, String apiid){

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(KEY_TYPE, type);
    values.put(KEY_TITLE, title);
    values.put(KEY_SUBTITLE, subtitle);
    values.put(KEY_APIID, apiid);
    // the code you have to add
    int count = getProfilesCount(); // check for number of records
    if(count == 10) {
        db.execSQL("DELETE FROM " + TABLE_NAME+ " ORDER BY  "+KEY_ID+"LIMIT 1"); // will delete oldest record
    } // add till here

    long id = db.insert(TABLE_ITEM, null, values); // insert to 1st row
    db.close(); // Closing database connection

    //Log.d(TAG, "New profile settings inserted into sqlite: " + id);
    System.out.println("sammy_New content inserted into sqlite: "+id);

}

答案 2 :(得分:0)

我认为触发器是这个问题的最佳答案。

This is the sample tutorial for how to make trigger in android.

在那里添加你的逻辑。

答案 3 :(得分:0)

您可以通过两种方式进行查询。

  1. 第一个是,处理那个得到总数没有行并检查,如果这些超过10,那么先删除一个旧行,然后运行insert命令,否则直接执行insert命令。
  2. 第二个问题是,不是自己处理这个条件而是将其交给触发器,它会自动处理这种情况 在这两种方式中,第二种方法更好,因为没有数据库在性能方面遇到问题,所以在触发的情况下,数据库只会有一次命中。