试了下xutils3的数据库操作,还是挺方便的,简单来说就是三个步骤:
一、建一个bean类,参考下面User.class
二、初始化数据库
三、调方法增删查改
bean类,User.class
package administrator.test;
import org.xutils.db.annotation.Column;
import org.xutils.db.annotation.Table;
@Table(name = "User")
public class User {
@Column(name = "id", isId = true)
private int id;
@Column(name = "name")
private String name;
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 User(String name) {
this.name = name;
}
//一定要构造一个无参方法
public User(){
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
然后就是使用例子
package administrator.test;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import org.xutils.DbManager;
import org.xutils.common.util.LogUtil;
import org.xutils.ex.DbException;
import org.xutils.x;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private DbManager db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initDb();
try {
add();
add();
find();
update();
find();
delete();
find();
} catch (DbException e) {
e.printStackTrace();
}
}
private void initDb() {
//本地数据的初始化
DbManager.DaoConfig daoConfig = new DbManager.DaoConfig()
.setDbName("xutils3_db") //设置数据库名
.setDbVersion(1) //设置数据库版本
.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) {
//数据库升级操作
}
});
db = x.getDb(daoConfig);
}
private void add() throws DbException {
User user = new User("用户1");
db.save(user);
LogUtil.i("---保存数据");
}
private void find() throws DbException {
List<User> list = db.findAll(User.class);
LogUtil.i("---" + list.toString());
}
private void update() throws DbException {
List<User> list = db.findAll(User.class);
User user = list.get(0);
user.setName("更换姓名");
db.update(user);
LogUtil.i("---更新数据");
}
private void delete() throws DbException {
List<User> list = db.findAll(User.class);
db.delete(list.get(0));
LogUtil.i("---删除数据");
}
}