java - SQLite数据库升级条件

标签 java android database sqlite

我有一个 android 报价应用程序,其中我使用 SQLite 数据库来存储报价。我已经使用这个 DatabaseHelper 启动了该应用程序的第一个版本。

public class DataBaseHandler extends SQLiteOpenHelper {
        private static String DB_PATH;
        private static String DB_NAME = "SuccessQuotes";
        private SQLiteDatabase myDataBase;
        private static int DATABASE_VERSION = 1;
        private final Context myContext;

        public DataBaseHandler(Context context) {

            super(context, DB_NAME, null, 1);
            this.myContext = context;
            DB_PATH = context.getDatabasePath(DB_NAME).toString();
            Log.e("path", DB_PATH);
        }

        // ==============================================================================


        public void createDataBase() throws IOException {

            boolean dbExist = checkDataBase();

            if (dbExist) {
                // do nothing - database already exist
            } else {

                this.getReadableDatabase();

                try {

                    copyDataBase();

                } catch (IOException e) {

                    throw new Error("Error copying database");

                }
            }

        }

        // ==============================================================================

        private boolean checkDataBase() {

            SQLiteDatabase checkDB = null;

            try {
                String myPath = DB_PATH;
                checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

            } catch (SQLiteException e) {

                // database does't exist yet.

            }

            if (checkDB != null) {

                checkDB.close();

            }

            return checkDB != null ? true : false;
        }

        // ==============================================================================

        private void copyDataBase() throws IOException {

            // Open your local db as the input stream
            InputStream myInput = myContext.getAssets().open(DB_NAME);

            // Path to the just created empty db
            String outFileName = DB_PATH;

            // Open the empty db as the output stream
            OutputStream myOutput = new FileOutputStream(outFileName);

            // transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }

            // Close the streams
            myOutput.flush();
            myOutput.close();
            myInput.close();

        }

        // ==============================================================================

        public void openDataBase() throws SQLException {

            // Open the database
            String myPath = DB_PATH;
            myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

        }

        // ==============================================================================

        @Override
        public synchronized void close() {

            if (myDataBase != null)
                myDataBase.close();

            super.close();

        }

        // ==============================================================================

        @Override
        public void onCreate(SQLiteDatabase db) {

        }

        // ==============================================================================

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }
    }

我的数据库 Activity 是:

public class DAO {

    // All Static variables

    private SQLiteDatabase database;
    private DataBaseHandler dbHandler;

    private static final String TABLE_QUOTES = "quotes";
    private static final String TABLE_AUTHORS = "authors";
    private static final String TABLE_SETTINGS = "settings";

    // Pages Table Columns names

    private static final String QU_ID = "_quid";
    private static final String QU_TEXT = "qu_text";
    private static final String QU_AUTHOR = "qu_author";
    private static final String QU_FAVORITE = "qu_favorite";
    private static final String QU_WEB_ID = "qu_web_id";

    private static final String AU_ID = "_auid";
    private static final String AU_NAME = "au_name";
    private static final String AU_PICTURE = "au_picture";
    private static final String AU_PICTURE_SDCARD = "au_picture_sdcard";
    private static final String AU_WEB_ID = "au_web_id";

    // ==============================================================================

    public DAO(Context context) {
        dbHandler = new DataBaseHandler(context);
        try {

            dbHandler.createDataBase();

        } catch (IOException ioe) {

            throw new Error("Unable to create database");

        }
        try {

            dbHandler.openDataBase();

        } catch (SQLException sqle) {

            throw sqle;

        }
//      Log.e("path2", context.getDatabasePath("SuccessQuotes").toString());
        // open();
    }


    // ==============================================================================

    // Getting All Quotes
    public Cursor getQuotes(String start) {
        // Select All Query

        String limit = "15";

        if (start.equals("5000")) {
            String query_count = "SELECT COUNT(" + QU_ID + ") AS count FROM "
                    + TABLE_QUOTES;
            Cursor c_count = database.rawQuery(query_count, null);
            c_count.moveToFirst();
            Integer count = c_count.getInt(c_count.getColumnIndex("count"));
            limit = String.valueOf(count);
        }
        String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
                + TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
                + " ORDER BY " + QU_WEB_ID + " DESC "+ " LIMIT " + start + ", " + limit;
        //Log.i("query",query);
        Cursor cursor = database.rawQuery(query, null);

        cursor.moveToFirst();
        return cursor;

    }

    // ==============================================================================

    // Getting All Quotes
    public Cursor getFavoriteQuotes(String start) {
        // Select All Query
        String limit = "15";

        String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
                + TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
                + " WHERE " + QU_FAVORITE + " = " + "1"+" ORDER BY " + QU_WEB_ID + " DESC  "+ " LIMIT " + start + ", " + limit;
        Cursor cursor = database.rawQuery(query, null);

        cursor.moveToFirst();
        return cursor;

    }

    //======================================================================

    // Getting Fav Quote from ID
        public String getFavQuotes(String strkey_id) {
            // Select All Query
            String fav = "";
            String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
                    + TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
                    + " WHERE " + QU_FAVORITE + " = " + "1 AND " + QU_ID + " = " +strkey_id;
            Cursor cursor = database.rawQuery(query, null);

            if(cursor.getCount() != 0)
            {
                cursor.moveToFirst();
                fav = cursor.getString(cursor.getColumnIndex(QU_FAVORITE));

            }
            return fav;

        }

    // ==============================================================================

    // Getting All Author Quotes
    public Cursor getAuthorQuotes(String authorID,String start) { 
        // Select All Query
        String limit="15";
        String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
                + TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
                + " WHERE " + QU_AUTHOR + " = " + authorID + " ORDER BY "+ QU_WEB_ID +" DESC  "+ " LIMIT " + start + ", " + limit;
        Cursor cursor = database.rawQuery(query, null);

        cursor.moveToFirst();
        return cursor;

    }

    // ==============================================================================

    // Getting Selected Quote
    public Cursor getOneQuote(String quoteID) {
        // Select All Query

        String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
                + TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
                + " WHERE " + QU_ID + " = '" + quoteID + "'";
        Cursor cursor = database.rawQuery(query, null);

        cursor.moveToFirst();
        return cursor;

    }

    // ==============================================================================

    public void addOrRemoveFavorites(String id, String value) {



        ContentValues values = new ContentValues();
        values.put(QU_FAVORITE, value);

        // Update Row
//      database.update(TABLE_QUOTES, values, QU_ID + "=?", new String[] { id });
        database.update(TABLE_QUOTES, values, QU_ID + "=?", new String[] { id });
    }

    // ==============================================================================

    // Getting All Authors
    public Cursor getAllAuthors() {
        // Select All Query

        String query = "SELECT *, COUNT(" + QU_AUTHOR + ") AS count FROM "
                + TABLE_AUTHORS + " LEFT JOIN " + TABLE_QUOTES + " ON " + AU_WEB_ID
                + " = " + QU_AUTHOR + " GROUP BY  " + AU_NAME ;
        Cursor cursor = database.rawQuery(query, null);

        cursor.moveToFirst();
        return cursor;

    }

    // ==============================================================================

    // Getting Quotes Count
    public Integer getQuotesCount() {

        String query = "SELECT COUNT(" + QU_TEXT + ") AS count FROM "
                + TABLE_QUOTES;
        Cursor cursor = database.rawQuery(query, null);
        cursor.moveToFirst();
        Integer count = cursor.getInt(cursor.getColumnIndex("count"));

        return count;

    }

    // ==============================================================================

    // Getting Quote ID
    public Integer getQotdId() {

        String query = "SELECT " + QU_ID + " FROM " + TABLE_QUOTES
                + " ORDER BY RANDOM() LIMIT 1";
        Cursor cursor = database.rawQuery(query, null);
        cursor.moveToFirst();
        Integer id = cursor.getInt(cursor.getColumnIndex(QU_ID));

        return id;

    }

    // ==============================================================================

    public void updateSetting(String field, String value) {
        open();
        ContentValues values = new ContentValues();
        values.put(field, value);

        // Update Row
        database.update(TABLE_SETTINGS, values, null, null);
    }

    // ==============================================================================

    public Cursor getSettings() {
        open();
        String query = "SELECT * FROM " + TABLE_SETTINGS;
        Cursor cursor = database.rawQuery(query, null);

        cursor.moveToFirst();
        return cursor;
    }

    // ==============================================================================

    public int getLastAuthor() {

        String query = "SELECT " + AU_WEB_ID + " FROM " + TABLE_AUTHORS
                + " ORDER BY " + AU_WEB_ID + " DESC LIMIT 1";

        Cursor cursor = database.rawQuery(query, null);

        cursor.moveToFirst();
        return cursor.getInt(cursor.getColumnIndex(AU_WEB_ID));

    }

    // ==============================================================================

    public int getLastQuote() {
        String query = "SELECT " + QU_WEB_ID + " FROM " + TABLE_QUOTES
                + " ORDER BY " + QU_WEB_ID + " DESC LIMIT 1";

        Cursor cursor = database.rawQuery(query, null);

        cursor.moveToFirst();
        return cursor.getInt(cursor.getColumnIndex(QU_WEB_ID));

    }

    // ==============================================================================

    public void addAuthor(String au_name, String au_picture, int au_web_id) {
        open();     

        ContentValues v = new ContentValues();
        v.put(AU_NAME, au_name);
        v.put(AU_PICTURE, au_picture);
        v.put(AU_PICTURE_SDCARD, 1);        
        v.put(AU_WEB_ID, au_web_id);

        database.insert(TABLE_AUTHORS, null, v);

    }

    // ==============================================================================

    public void addQuote(String qu_text, int qu_author, int qu_web_id) {
        open();
        ContentValues v = new ContentValues();
        v.put(QU_TEXT, qu_text);        
        v.put(QU_AUTHOR, qu_author);
        v.put(QU_FAVORITE, "0");        
        v.put(QU_WEB_ID, qu_web_id);

        database.insert(TABLE_QUOTES, null, v);

    }

    // ==============================================================================

    public void open() throws SQLException {
//      database = dbHandler.getReadableDatabase();
        database = dbHandler.getWritableDatabase();

    }

    // ==============================================================================

    public void closeDatabase() {
        dbHandler.close();
    }

现在,如果我想用更多报价更新应用程序,我应该进行哪些更改,以便新老用户不会遇到任何问题?

我知道数据库版本应该增加,我会的,但是我应该在 onUpgrade 方法中放入什么?

我不是 Android 开发专家,所以如果可能的话请多解释一下,我将非常感谢。 谢谢

谢谢

最佳答案

Java 文档几乎解释了需要做什么。

来自 Java 文档

当数据库需要升级时调用。实现情况 应该使用此方法删除表、添加表或执行其他任何操作 需要升级到新的架构版本。

我们所做的是,只要我们更改了表架构,就更改表。 此外,如果需要,您还可以执行一些数据迁移。基本上它是您获得的一个钩子(Hook),您可以执行任何类型的兼容性逻辑。

干杯,

索拉夫

关于java - SQLite数据库升级条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35617047/

相关文章:

java - 安卓服务未启动

android - 如何将图像分成两部分?

mysql - 酒店预订系统 : How to store individual price for each night of a reservation?

java - 为什么即使提供了初始容量,我们也不能在将元素添加到第 (n-1) 个索引之前将元素添加到列表中的第 n 个索引

java - 根据给定值和父 ID 创建树

java - 自定义相机 android 中的闪光灯

jquery - 是否有一个可以与jquery一起使用的云数据库API?

database - 实现数据库修订的最佳做法是什么?

java - Spring JPA : Saving an entity Object in database

android - Dagger 2 构造函数注入(inject)等