Android数据库三:xutils3框架之数据库使用详解!

1.添加依赖

compile 'org.xutils:xutils:3.5.0'

2.github地址

https://github.com/wyouflf/xUtils3

3.添加权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

4.初始化

// 在application的onCreate中初始化
@Override
public void onCreate() {
    super.onCreate();
    x.Ext.init(this);
    x.Ext.setDebug(BuildConfig.DEBUG); // 是否输出debug日志, 开启debug会影响性能.
    ...
}

5.实体类

package com.example.xutils3.db;

import org.xutils.db.annotation.Column;
import org.xutils.db.annotation.Table;

/**
 * Created by xiaoyehai on 2016/11/8.
 */
@Table(name = "UserInfo")
public class UserInfo {

    @Column(name = "id", isId = true, autoGen = true)
    private int id;

    @Column(name = "name")
    private String name;

    @Column(name = "age")
    private int age;

    @Column(name = "sex")
    private String sex;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

6.XUtilsManager

package com.example.xutils3.db;

import org.xutils.DbManager;
import org.xutils.x;

import java.io.File;

/**
 * Created by xiaoyehai on 2016/11/8.
 */
public class XUtilsManager {

    private static XUtilsManager mInstance;

    private DbManager dbManager;

    private XUtilsManager() {
    }

    public static XUtilsManager getInstance() {
        if (mInstance == null) {
            synchronized (XUtilsManager.class) {
                if (mInstance == null) {
                    mInstance = new XUtilsManager();
                }
            }
        }
        return mInstance;
    }

    public DbManager getDbManager() {
        if (dbManager == null) {
            initDbManager();
        }
        return dbManager;
    }

    private void initDbManager() {
        File dbFile = new File("/sdcard/xutils/db");
        if (!dbFile.exists()) {
            dbFile.mkdirs();
        }
        DbManager.DaoConfig config = new DbManager.DaoConfig()
                .setDbDir(dbFile) //数据库路径
                .setDbName("xutil") //数据库名
                .setDbVersion(1) //设置数据库版本
                .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                    @Override
                    public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
                        // TODO: 2016/11/8 数据库更新操作
//                        try {
                        //                            db.addColumn(UserInfo.class, "test");
                        //                        } catch (DbException e) {
                        //                            e.printStackTrace();
                        //                        }
                    }
                });
        dbManager = x.getDb(config);
    }
}



7. 数据库增删改查方法

package com.example.xutils3.db;

import org.xutils.DbManager;
import org.xutils.common.util.KeyValue;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;

import java.util.List;

/**
 * 数据库增删改查方法
 * Created by xiaoyehai on 2018/1/16 0016.
 */

public class UserInfoDao {

    private final DbManager mDbManager;

    public UserInfoDao() {
        mDbManager = XUtilsManager.getInstance().getDbManager();
    }

    /**
     * 添加数据
     *
     * @param list
     */
    public void addData(List<UserInfo> list) {
        try {
            //mDbManager.delete(UserInfo.class);
            //mDbManager.save(list);
            //mDbManager.saveBindingId(list);
            //mDbManager.saveOrUpdate(list);

            mDbManager.replace(list); //保存或更新实体类或实体类的List到数据库, 根据id和其他唯一索引判断数据是否存在.
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除全部数据
     */
    public void deleteAllData() {
        try {
            mDbManager.delete(UserInfo.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据id删除数据
     */
    public void deleteDataById(int id) {
        try {
            mDbManager.deleteById(UserInfo.class, id); //删除指定id数据
            //根据指定条件删除
            // mDbManager.delete(UserInfo.class, WhereBuilder.b("sex", "=", "女"));
            //mDbManager.delete(UserInfo.class, WhereBuilder.b("id", ">=", "50").and("id", "<=", "100"));
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据条件删除数据
     */
    public void deleteDataByCondition(WhereBuilder whereBuilder) {
        try {
            //根据指定条件删除
            // mDbManager.delete(UserInfo.class, WhereBuilder.b("sex", "=", "女"));
            //mDbManager.delete(UserInfo.class, WhereBuilder.b("id", ">=", "50").and("id", "<=", "100"));

            mDbManager.delete(UserInfo.class, whereBuilder);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新数据:修改表中的某一条数据
     */
    public void updateData(UserInfo userInfo, String... columnNames) {
        try {
            mDbManager.update(userInfo, columnNames);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    /**
     * 修改表中的某些数据
     *
     * @param whereBuilder1
     * @param whereBuilder2
     * @param keyValue
     */
    public void updateData2(WhereBuilder whereBuilder1, WhereBuilder whereBuilder2, KeyValue... keyValue) {
        try {
            mDbManager.update(UserInfo.class, whereBuilder1.or(whereBuilder2), keyValue);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查找所有数据
     */
    public List<UserInfo> findAllData(Class<UserInfo> tclass) {
        try {
            //UserInfo first = mDbManager.findFirst(tclass);查询第一条数据
            return mDbManager.findAll(tclass);
        } catch (DbException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据条件查询
     */
    public List<UserInfo> findDataByCondition(Class<UserInfo> tclass, WhereBuilder whereBuilder) {
        try {
            List<UserInfo> allList = mDbManager.selector(tclass).where(whereBuilder).findAll();
            return allList;
        } catch (DbException e) {
            e.printStackTrace();
        }
        return null;
    }
}

8.Activity

package com.example.xutils3.db;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import com.example.xutils3.R;

import org.xutils.common.util.KeyValue;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * /**
 * XUtils3的数据库模块:
 * 1.DbManager的初始化
 * 2.实体类种要对表名和列名加注解
 */

@ContentView(R.layout.activity_db)
public class DBActivity extends AppCompatActivity {

    @ViewInject(R.id.tv)
    private TextView tv;

    private UserInfoDao mUserInfoDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);

        mUserInfoDao = new UserInfoDao();
    }

    /**
     * 增加数据
     *
     * @param view
     */
    @Event(R.id.btn_save)
    private void save(View view) {
        List<UserInfo> list = new ArrayList<>();
        UserInfo userInfo;
        for (int i = 0; i < 50; i++) {
            userInfo = new UserInfo();
            //useInfo.setId(1); //可以不设置,主键
            userInfo.setName("糖糖" + i);
            userInfo.setAge(10 + i);
            userInfo.setSex("女");

            list.add(userInfo);
        }
        mUserInfoDao.addData(list);
    }

    /**
     * 删除数据
     *
     * @param view
     */
    @Event(R.id.btn_delete)
    private void delete(View view) {
        mUserInfoDao.deleteAllData(); //删除所有数据
    }

    /**
     * 更新数据
     *
     * @param view
     */
    @Event(R.id.btn_update)
    private void update(View view) {
        //1.修改表中的某一条数据
        UserInfo userInfo = new UserInfo();
        userInfo.setId(10);
        userInfo.setName("dd");
        userInfo.setAge(25);
        mUserInfoDao.updateData(userInfo, "name", "age");

        //2.修改表中的某些数据
        KeyValue nameValue = new KeyValue("name", "李钦");
        KeyValue ageValue = new KeyValue("age", "123");
        WhereBuilder whereBuilder1 = WhereBuilder.b("id", "=", "20");
        WhereBuilder whereBuilder2 = WhereBuilder.b("id", "=", "30");
        mUserInfoDao.updateData2(whereBuilder1, whereBuilder2, nameValue, ageValue);
    }

    /**
     * 查找数据
     *
     * @param view
     */
    @Event(R.id.btn_find)
    private void find(View view) {
        //查询全部数据
        List<UserInfo> allList = mUserInfoDao.findAllData(UserInfo.class);

        //条件查询
        // List<UserInfo> list = db.selector(UserInfo.class).where("name", "=", "剑圣1").findAll();
        //WhereBuilder whereBuilder = WhereBuilder.b("name", "=", "糖糖5");
        //List<UserInfo> allList = mUserInfoDao.findDataByCondition(UserInfo.class, whereBuilder);

        if (allList != null) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < allList.size(); i++) {
                UserInfo info = allList.get(i);
                sb.append(info.getId() + ",").append(info.getName() + ",").append(info.getAge() + ",")
                        .append(info.getSex()).append("\n");
            }
            tv.setText(sb);
        }
    }
}
展开阅读全文

没有更多推荐了,返回首页