How to create and update an android-SQLite database, add, delete, and change its usage

Posted by xoligy on Sun, 26 May 2019 19:23:42 +0200

Introduction to SQLite

1. Introduction
Android embedded relational database - SQLite.SQLite is a lightweight relational database. It is fast, takes little resources and usually only needs a few hundred K s of memory, making it especially suitable for use on mobile devices.SQLite supports standard SQL syntax and follows database ACID transactions.SQLite is much simpler to use a general database where all the information (such as tables, views, and so on) is contained in one file.This file can be freely copied to another directory or other machine.

2. Data Types

data type describe
INTEGER Value is an integer
TEXT Character string
REAL A floating number stored as an 8-byte IEEE floating tag ordinal
VARCHAR String length not exceeding 4000
CHAR String length not exceeding 254
BLOB Store as input data without changing format
DATA Specific date
TIME Hours and seconds
NULL Value is empty

2. Use

1.SQLiteOpenHelper

To make it easier for us to manage databases, Android provides a helper class, SQLiteOpenHelper, that allows us to create and upgrade databases very easily.When the getWritableDatabase() or getReadableDatabase() methods of this class are called in a program, if there is no data at that time, the Android system will automatically generate a database.

 private static class DataBaseManagementHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "user_data";
    private static final String TABLE_NAME = "users";
     //Create user book table
    private static final String DB_CREATE = "CREATE TABLE " + TABLE_NAME + " ("
            + ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + USER_NAME + " TEXT,"
            + USER_PWD + " TEXT" + ");";
        DataBaseManagementHelper(Context context) {
            super(context, DB_NAME, null, DB_VERSION);
        }

        //This implements three functions within SQLiteOpenHelper:
        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.i(TAG,"db.getVersion()="+db.getVersion());
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME + ";");
            db.execSQL(DB_CREATE);
            Log.i(TAG, "db.execSQL(DB_CREATE)");
            Log.e(TAG, DB_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.i(TAG, "DataBaseManagementHelper onUpgrade");
            onCreate(db);
        }
         @Override
        public void onOpen(SQLiteDatabase db) {
            super.onOpen(db);
            //This is not commonly used
        }
    }

2. Here is a specific code management database class

/**
 * @author daxue
 * @version Created at 11:27:01 a.m. on 08-23, 2018
 */

public class RunRecordManager {
    private static final String TAG = "RunRecordManager";
    private static final String DB_NAME = "runrecord_data";//Database Name
    private static final String TABLE_NAME = "runrecord";//Table Name
    //Used when updating a database
    private static String CREATE_TEMP_BOOK = "alter table runrecord rename to _temp";
    private static String INSERT_DATA = "insert into runrecord select *,' ',' ',' ' from _temp";
    private static String DROP_BOOK = "drop table _temp";

    private static final int DB_VERSION = 2;//Database Version Number
    private Context mContext = null;

    private SQLiteDatabase mSQLiteDatabase = null;
    private DataBaseManagementHelper mDatabaseHelper = null;

    public RunRecordManager(Context context) {
        mContext = context;
        Log.i(TAG, "UserDataManager construction!");
    }

    //DataBaseManagementHelper inherits from SQLiteOpenHelper
    private static class DataBaseManagementHelper extends SQLiteOpenHelper {

        DataBaseManagementHelper(Context context) {
            super(context, DB_NAME, null, DB_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.i(TAG,"db.getVersion()="+db.getVersion());
            db.execSQL(getSql());
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.i(TAG, "DataBaseManagementHelper onUpgrade");
                switch (newVersion) {
                    case 4:
                        db.execSQL(CREATE_TEMP_BOOK);
                        db.execSQL(getSql());
                        db.execSQL(INSERT_DATA);
                        db.execSQL(DROP_BOOK);
                        break;
                }

        }
    }
    //sql statement to create database table
    private static String getSql(){
        String sql = String.format("create table %s ( %s INTEGER PRIMARY KEY AUTOINCREMENT,"
                        + " %s TEXT, %s TEXT,%s TEXT, %s TEXT, %s TEXT);",
                TABLE_NAME,
                PcrConfig.Columns._ID,
                PcrConfig.Columns.USER_NAME,
                PcrConfig.Columns.EXPER_ID,
                PcrConfig.Columns.EXPER_NAME,
                PcrConfig.Columns.CREAT_TIME,
                PcrConfig.Columns.RUN_TIME);

        if(PcrConfig.debug) {
            Log.d(TAG, "sql:"+ sql);
        }
        return sql;
    }


    //Open database
    public void openDataBase() throws SQLException {
        mDatabaseHelper = new DataBaseManagementHelper(mContext);
        mSQLiteDatabase = mDatabaseHelper.getWritableDatabase();
    }
    //close database
    public void closeDataBase() throws SQLException {
        mDatabaseHelper.close();
    }
    //Add records (insert data)
    public long insertRecordData(RunRecordBean data) {
        ContentValues values = new ContentValues();
        values.put(PcrConfig.Columns.USER_NAME, data.getUserName());
        values.put(PcrConfig.Columns.EXPER_NAME, data.getExperName());
        values.put(PcrConfig.Columns.EXPER_ID, data.getId());
        values.put(PcrConfig.Columns.CREAT_TIME, data.getCreatTime());
        values.put(PcrConfig.Columns.RUN_TIME, data.getRunTime());
        return mSQLiteDatabase.insert(TABLE_NAME, PcrConfig.Columns._ID, values);
    }

    public Cursor fetchUserData(int id) throws SQLException {
        Cursor mCursor = mSQLiteDatabase.query(false, TABLE_NAME, null, PcrConfig.Columns._ID
                + "=" + id, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
    //
    public Cursor fetchAllUserDatas() {
        return mSQLiteDatabase.query(TABLE_NAME, null, null, null, null, null,
                null);
    }
    //Delete users based on id
    public boolean deleteUserData(int id) {
        return mSQLiteDatabase.delete(TABLE_NAME, PcrConfig.Columns._ID + "=" + id, null) > 0;
    }
    //Log off by user name
    public boolean deleteUserDatabyname(String name) {
        return mSQLiteDatabase.delete(TABLE_NAME, PcrConfig.Columns.USER_NAME + "='" + name+"'", null) > 0;
    }
    //Delete all users
    public boolean deleteAllUserDatas() {
        return mSQLiteDatabase.delete(TABLE_NAME, null, null) > 0;
    }
   //Update user information, such as changing passwords
    public boolean updateUserData(UserData userData) {
        //int id = userData.getUserId();
        String userName = userData.getUserName();
        String userPwd = userData.getUserPwd();
        ContentValues values = new ContentValues();
        values.put(USER_NAME, userName);
        values.put(USER_PWD, userPwd);
        return mSQLiteDatabase.update(TABLE_NAME, values,null, null) > 0;
        //return mSQLiteDatabase.update(TABLE_NAME, values, ID + "=" + id, null) > 0;
    }
    //Get all records
    public List<RunRecordBean> getAllUserDatas() {
        List<RunRecordBean> ret=new ArrayList<RunRecordBean>();
        try{
            Cursor cursor = mSQLiteDatabase.query(TABLE_NAME, null, null, null, null, null,
                    null);
            if(cursor != null){
                while(cursor.moveToNext()){
                    RunRecordBean value = new RunRecordBean();
                    String str = cursor.getString(cursor.getColumnIndex(PcrConfig.Columns.EXPER_ID));
                    value.setExperId(str);
                    str = cursor.getString(cursor.getColumnIndex(PcrConfig.Columns._ID));
                    value.setId(str);
                    str = cursor.getString(cursor.getColumnIndex(PcrConfig.Columns.USER_NAME));
                    value.setUserName(str);
                    str = cursor.getString(cursor.getColumnIndex(PcrConfig.Columns.EXPER_NAME));
                    value.setExperName(str);
                    str = cursor.getString(cursor.getColumnIndex(PcrConfig.Columns.CREAT_TIME));
                    value.setCreatTime(str);
                    str = cursor.getString(cursor.getColumnIndex(PcrConfig.Columns.RUN_TIME));
                    value.setRunTime(str);
                    ret.add(value);
                }
                cursor.close();
            }
        } catch (Exception e){
            Log.d(TAG, "getAllUserDatas Execption "+e.toString());
        }

        return ret;
    }

}

3. Use databases

  private RunRecordManager runrecManger=null;
  private void recRun() {
        if(runrecManger == null) {
            runrecManger = new RunRecordManager(this);
            runrecManger.openDataBase();
        }
        data.setUserName("daxue");
        data.setCreatTime("123");
        long flag = runrecManger.insertRecordData(data);

    }

4. Clear the database

public void clearDatabases() {
        deleteFilesByDirectory(new File("/data/data/"
                + context.getPackageName() + "/databases"));
    }

Topics: Database SQL SQLite Android