xUtils系列之DbUtils-查询

其实DbUtils的代码已经很清楚了,所以举个例子 来描述具体用法.

首先,建立一个实体类Person:

package com.example.entities;

import com.lidroid.xutils.db.annotation.Column;
import com.lidroid.xutils.db.annotation.Table;

@Table(name="person")
public class Person {
	private int id;
	
	@Column(column="name")
	private String name;
	
	@Column(column="hobby")
	private String hobby;

	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 getHobby() {
		return hobby;
	}

	public void setHobby(String hobby) {
		this.hobby = hobby;
	}
	
	@Override
	public String toString()
	{
		return "[id="+id+" name="+name+" hobby="+hobby+"]";
	}
	
}

新建一个MainActivity类,在onCreate函数里面可以这样用:

@Override
protected void onCreate(Bundle savedInstanceState){
	super.onCreate(savedInstanceState);
	ViewUtils.inject(this);
	initWebView();
	
	DbUtils db = DbUtils.create(this);
	try {
		db.dropTable(Person.class);
	} catch (DbException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	
	String[] names={"zhao","qian","sun","li","zhou","wu","zhen","wang"};
	String[] hobbys={"pingpong","pingpong","pingpong","football","football","basketball","basketball","basketball"};
	
	List list = new ArrayList();
	for(int i=0;i<8;++i)
	{
		Person p = new Person();
		p.setName(names[i]);
		p.setHobby(hobbys[i]);
		list.add(p);
	}
	
	try {
		db.saveAll(list);
		
		db.findAll(Child.class);
		db.findAll(Selector.from(Child.class).where("id", ">", 2));
		db.findById(Child.class, 1);
		db.findFirst(Child.class);
		db.findFirst(Selector.from(Child.class).where("id", ">", 2));
		
		db.findDbModelAll(DbModelSelector.from(Child.class).groupBy("hobby").having(WhereBuilder.b("id", ">", 2)));
		db.findDbModelFirst(DbModelSelector.from(Child.class).groupBy("hobby").having(WhereBuilder.b("id", ">", 2)));
		
		
		
		Cursor c = db.execQuery(new SqlInfo("select * from child;"));
		
		//findDbModelFirst和findDbModelAll相当是对execQuery做了再次封装,
		//返回的DbModel中,封装了通过列名获取value的方法,如:String getString(String columnName)等等.
		DbModel model = db.findDbModelFirst(new SqlInfo("select * from child;")); //采取原生sql语句,可以做多表查询操作
		List modellist = db.findDbModelAll(new SqlInfo("select * from child;"));

	} catch (DbException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
}


你可能感兴趣的:(xUtils)