您的位置:首页 > 数据库

XUtils3.0数据库的一些操作

2017-07-09 21:31 211 查看
在app的build中导入

compile 'org.xutils:xutils:3.5.0'


androidmanifas添加权限:

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


public class MyApplication extends Application {

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

}


新增一个数据库表的实体类:

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

/**
* Created by wjj on 2017/7/9.
*/

@Table(name = "child")
public class Child {

/**
* autoGen是否自增
*/
@Column(name = "id", isId = true, autoGen = false)
private int id;

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

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

@Column(name = "parentId" /*, property = "UNIQUE"//如果是一对一加上唯一约束*/)
private long parentId; // 外键表id

// 这个属性被忽略,不存入数据库
private String willIgnore;

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

//    @Column(name = "REGTIME")
//    private Date regTime;

//默认的构造方法必须写出,如果没有,这张表是创建不成功的
public Child() {
}

public Child(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}

public long getParentId() {
return parentId;
}

public void setParentId(long parentId) {
this.parentId = parentId;
}

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 String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getWillIgnore() {
return willIgnore;
}

public void setWillIgnore(String willIgnore) {
this.willIgnore = willIgnore;
}

public String getText() {
return text;
}

public void setText(String text) {
this.text = text;
}

@Override
public String toString() {
return "Child{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", parentId=" + parentId +
", willIgnore='" + willIgnore + '\'' +
", text='" + text + '\'' +
'}';
}

//    public Date getRegTime() {
//        return regTime;
//    }
//
//    public void setRegTime(Date regTime) {
//        this.regTime = regTime;
//    }
}


新建一个数据库帮助类:

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

/**
* Created by wjj on 2017/7/9.
*/

public class DatabaseOpenHelper {
private DbManager.DaoConfig daoConfig;
private static DbManager db;
private final String DB_NAME = "mydb";
private final int VERSION = 1;

private DatabaseOpenHelper() {
daoConfig = new DbManager.DaoConfig()
.setDbName(DB_NAME)
.setDbVersion(VERSION)
.setDbOpenListener(new DbManager.DbOpenListener() {
@Override
public void onDbOpened(DbManager db) {
db.getDatabase().enableWriteAheadLogging();
//开启WAL, 对写入加速提升巨大(作者原话)
}
})
.setDbUpgradeListener(new DbManager.DbUpgradeListener() {
@Override
public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
//数据库升级操作TODO: ...
// db.addColumn(...);
// db.dropTable(...);
// ...
//                        try {
//                            db.addColumn(Child.class, "REGTIME");//Child表,新增列名。记得修改之后,VERSION增加数值
//                            //db.saveOrUpdate(Child.class);
//                        } catch (DbException e) {
//                            e.printStackTrace();
//                        }
}
});
db = x.getDb(daoConfig);
}

public static DbManager getInstance() {
if (db == null) {
DatabaseOpenHelper databaseOpenHelper = new DatabaseOpenHelper();
}
return db;
}
}


针对具体的child表,建立一个实用类:

import android.util.Log;

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;

import scut.carson_ho.search_layout.bean.Child;

/**
* Created by wjj on 2017/7/9.
*/

public class ChildDb {

private DbManager db;

private boolean succeed;//操作是否成功,true是,false否
boolean idDesc = true;//是否倒序,默认false

private List<Child> list = null;

private Child child;

long count = 0;

//接收构造方法初始化的DbManager对象
public ChildDb() {
db = DatabaseOpenHelper.getInstance();
}

/**
* 将Child实例存进数据库
* 保存新增
*/
public void saveChild(Child child) {
try {
db.save(child);
} catch (DbException e) {
e.printStackTrace();
}
}

/**
* 新增或更新
*
* @param child
*/
public void saveOrUpdate(Child child) {
try {
db.saveOrUpdate(child);
// Log.d("xyz","save succeed!");
} catch (DbException e) {
e.printStackTrace();
}
}

/**
* 读取所有Child信息
*
* @return
*/
public List<Child> loadChildAll() {

try {
list = db.selector(Child.class).findAll();
} catch (DbException e) {
e.printStackTrace();
}
return list;
}

/**
* 根据名字读取Child信息
*
* @return
*/
public List<Child> loadChildByName(String name) {

try {
list = db.selector(Child.class).where("name", "==", name).findAll();
} catch (DbException e) {
e.printStackTrace();
}
return list;
}

public List<Child> loadChildByIdsBetween(String[] ids) {
ids = new String[]{"1", "5"};

try {
list = db.selector(Child.class).where("id", "between", ids).findAll();
} catch (DbException e) {
e.printStackTrace();
}
return list;
}

/**
* 根据id删除
*
* @param id
* @return
*/
public boolean deleteById(int id) {
try {
db.deleteById(Child.class, 5);
succeed = true;
} catch (DbException e) {
succeed = false;
e.printStackTrace();
}
return succeed;
}

/**
* 删除表
*
* @throws DbException
*/
private void delTable() throws DbException {
db.dropTable(Child.class);
}

/**
* 查询表中的数据
*
* @param
* @throws DbException
*/
private void selelctDB() throws DbException {
//查询数据库表中第一条数据
Child first = db.findFirst(Child.class);
Log.i("JAVA", first.toString());
//添加查询条件进行查询
//第一种写法:
WhereBuilder b = WhereBuilder.b();
b.and("id", ">", 2); //构造修改的条件
b.and("id", "<", 4);
List<Child> all = db.selector(Child.class).where(b).findAll();//findAll():查询所有结果
for (Child childInfo : all) {
Log.i("JAVA", childInfo.toString());
}
//第二种写法:
List<Child> all2 = db.selector(Child.class).where("id", ">", 2).and("id", "<", 4).findAll();
for (Child childInfo : all2) {
Log.i("JAVA", childInfo.toString());
}
}

/**
* 修改表中的数据
*
* @throws DbException
*/
private void updateTable() throws DbException {
//第一种写法:
Child first = db.findFirst(Child.class);
first.setName("zhansan2");
db.update(first, "c_name"); //c_name:表中的字段名
//第二种写法:
WhereBuilder b = WhereBuilder.b();
b.and("id", "=", first.getId()); //构造修改的条件
KeyValue name = new KeyValue("c_name", "zhansan3");
db.update(Child.class, b, name);
//第三种写法:
first.setName("zhansan4");
db.saveOrUpdate(first);
}

Child findByIdsIn() {
Child mc = null;
try {
mc = db.selector(Child.class).where("id", "in", new int[]{1, 3, 6}).findFirst();
} catch (DbException e) {
e.printStackTrace();
}

return mc;
}

/**
* 获取某些数据的个数
*
* @return
*/
long getCountBy() {

try {
count = db.selector(Child.class).where("name", "LIKE", "w%").and("age", ">", 32).count();
} catch (DbException e) {
count = 0;
e.printStackTrace();
}
return count;
}

/**
* 查找名字有某个字符串的列表
*
* @param strLike
* @return
*/
public List<Child> findNameByLike(String strLike) {

try {
list = db.selector(Child.class).where("name", "LIKE", "%" + strLike + "%").findAll();
} catch (DbException e) {
e.printStackTrace();
}

return list;
}

/**
* 最小的id
*
* @return
* @throws DbException
*/
public int findMinId() throws DbException {

child = db.selector(Child.class).orderBy("id").findFirst();

return child.getId();
}

/**
* 最大的id
*
* @return
* @throws DbException
*/
public int findMaxId() throws DbException {

child = db.selector(Child.class).orderBy("id", idDesc).findFirst();

return child.getId();
}

List<Child> findList() throws DbException {
list = db.selector(Child.class)
.where("name", "like", "%kevin%")
.and("email", "=", "caolbmail@gmail.com")
.orderBy("id", idDesc)
.limit(2) //只查询两条记录
.offset(2) //偏移两个,从第三个记录开始返回,limit配合offset达到sqlite的limit m,n的查询
.findAll();
return list;
}

}


具体的操作,在Activity中:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.xutils.ex.DbException;

import java.util.List;

/**
* Created by wjj on 2017/7/9.
*/

public class TestDbActivity extends AppCompatActivity {
private MyApplication appApplication;

private TextView tv_db;

/**
* 数据显示listview
*/
private ListView mListView;

StringBuilder sb;
ChildDb cDb;
int maxId = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.db_activity);

tv_db = (TextView) findViewById(R.id.tv_db);
mListView = (ListView) findViewById(R.id.lv_db);

sb = new StringBuilder();

appApplication = new MyApplication();

// db = x.getDb(appApplication.getDaoConfig());
cDb = new ChildDb();

try {
maxId = cDb.findMaxId();
} catch (DbException e) {
maxId = 0;
e.printStackTrace();
}

maxId += 1;
Child child = new Child();
child.setId(maxId);
child.setName("明小明");
// child.setRegTime(new Date().);
// child.setEmail("gmaillove@qq.com");

cDb.saveOrUpdate(child);
Toast.makeText(TestDbActivity.this, "maxId=" + maxId, Toast.LENGTH_SHORT).show();

maxId++;
Child child2 = new Child(maxId, "小小", "fdfd@163.com");
cDb.saveOrUpdate(child2);

List<Child> mlc = cDb.findNameByLike("小");
if (mlc != null) {
sb.append(mlc.size() + "\n");
for (Child mChild : mlc) {
Log.d("xyz", mChild.toString());
sb.append(mChild.toString() + "\n");
}
}

tv_db.setText(sb.toString());

}

}

官网demo的混淆代码:

################### region for xUtils
-keepattributes Signature,*Annotation*
-keep public class org.xutils.** {
public protected *;
}
-keep public interface org.xutils.** {
public protected *;
}
-keepclassmembers class * extends org.xutils.** {
public protected *;
}
-keepclassmembers @org.xutils.db.annotation.* class * {*;}
-keepclassmembers @org.xutils.http.annotation.* class * {*;}
-keepclassmembers class * {
@org.xutils.view.annotation.Event <methods>;
}
#################### end region
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android db 数据量