Android数据库框架的使用——OrmLite

  • 下载ormlite-core、ormlite-android

使用时直接继承OrmLiteSqliteOpenHelper

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

    // db名称
    private static final String TABLE_NAME = "name.db";
    // db版本
    private static final int DB_VERSION = 1;


    private Map daos = new HashMap();

    private DatabaseHelper(Context context) {
        super(context, TABLE_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase database,
                         ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, GroupChat.class)

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

//数据库升级时会执行该方法
    @Override
    public void onUpgrade(SQLiteDatabase database,
                          ConnectionSource connectionSource, int oldVersion, int newVersion) {
        // 升级联系人表,增加姓名拼音与拼音简写两个字段
        if (newVersion > 1 && oldVersion == 1) {
            String addPYSQL = "ALTER TABLE tb_contact ADD pinyin VARCHAR DEFAULT null;";
            String addSPYSQL = "ALTER TABLE tb_contact ADD spinyin VARCHAR DEFAULT null;";
            database.beginTransaction();
            try {
                database.execSQL(addPYSQL);
                database.execSQL(addSPYSQL);
                database.setTransactionSuccessful();
            } finally {
                database.endTransaction();
            }
        }

    }

    private static DatabaseHelper instance;

    /**
     * 单例获取该Helper
     *
     * @param context
     * @return
     */
    public static synchronized DatabaseHelper getHelper(Context context) {
        context = context.getApplicationContext();
        if (instance == null) {
            synchronized (DatabaseHelper.class) {
                if (instance == null)
                    instance = new DatabaseHelper(context);
            }
        }

        return instance;
    }

    /**
     * 获取Dao
     *
     * @param clazz
     * @return
     * @throws SQLException
     */
    public synchronized Dao getDao(Class clazz) throws SQLException {
        Dao dao = null;
        String className = clazz.getSimpleName();

        if (daos.containsKey(className)) {
            dao = daos.get(className);
        }
        if (dao == null) {
            dao = super.getDao(clazz);
            daos.put(className, dao);
        }
        return dao;
    }

    /**
     * 释放资源
     */
    @Override
    public void close() {
        super.close();

        for (String key : daos.keySet()) {
            Dao dao = daos.get(key);
            dao = null;
        }
    }

}
package com.feng.ormlite;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

/**
 * Created by fengcz on 2018/11/24.
 */
@DatabaseTable(tableName = "group")
public class GroupChat {
    @DatabaseField(generatedId = true, columnName = "id", unique = true)
    private int id;
    @DatabaseField(columnName = "groupName", canBeNull = true)
    private String groupName;
    @DatabaseField(columnName = "groupId", canBeNull = true)
    private String groupId;

    /**
     * 此构造方法必须存在
     */
    public GroupChat() {
    }

    /**
     * 有这个构造方法必须重写上一个参数为空的构造函数
     *
     * @param groupName
     * @param groupId
     */
    public GroupChat(String groupName, String groupId) {
        this.groupName = groupName;
        this.groupId = groupId;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getGroupName() {
        return groupName;
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }
}

  • GroupDao进行增删改查
package com.feng.ormlite;

import android.content.Context;
import android.widget.Toast;

import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by fengcz on 2018/11/24.
 */

public class GroupChatDao {
    private Context context;
    private Dao collectionDaoOpe;
    private DatabaseHelper helper;

    public GroupChatDao(Context context) {
        this.context = context;
        try {
            helper = DatabaseHelper.getHelper(context.getApplicationContext());
            collectionDaoOpe = helper.getDao(GroupChat.class);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过字段查询
     *
     * @param groupNmae
     * @return
     */

    public List queryByGroupName(String groupNmae) {
        try {
            return collectionDaoOpe.queryBuilder().where().eq("groupName", groupNmae).query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询全部
     *
     * @return collections of data
     */
    public List queryGroupAll() {
        try {
            return collectionDaoOpe.queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * insert a new data
     * @param user user
     */
    public void addGroup(GroupChat user) {
        try {
            collectionDaoOpe.create(user);
            Toast.makeText(context, "添加成功", Toast.LENGTH_SHORT).show();
        } catch (SQLException e) {
            e.printStackTrace();
            Toast.makeText(context, "添加失败", Toast.LENGTH_SHORT).show();
        }
    }

    public void delete() {
        try {
            collectionDaoOpe.deleteBuilder().delete();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


}

具体使用

GroupChatDao chatDao = new GroupChatDao(this);

//增加一条数据
GroupChat chat = new GroupChat(name, id);
chatDao.addGroup(chat);

你可能感兴趣的:(Android数据库框架的使用——OrmLite)