GreenDao框架提供非常便利的数据库操作,开发者并不用编写原生的SQL语句。
单表查询:
表名:Son
字段名:姓名, 年龄, 性别
//条件查询 equals,查询儿子表中,姓名为 Jack的对象,eq对象是唯一的
Son son = sonDao.queryBuilder().Where(SonDao.Properties.姓名.eq("jack")).unique;
//查询儿子表中,姓名 类似like 为 Jack的对象,不止一个
List<Son> son_list = sonDao.queryBuilder().where(SonDao.Properties.姓名.like("jack")).list();
//查询 儿子表中, 年龄 >20 并且 年龄 < 40的对象,between不止一个
List<Son> son_list1 = sonDao.queryBuilder().where(SonDao.Properties.年龄.between(20,40)).list();
//查询 儿子表中, 年龄 > 30的 对象, great 不止一个
List<Son> son_list2 = sonDao.queryBuilder().where(SonDao.Properties.年龄.gt(30)).list();
//查询 儿子表中, 年龄>=20 的对象, ge(great equals)不止一个
List<Son> son_list5 = sonDao.queryBuilder().where(SonDao.Properties.年龄.ge(20)).list();
//查询 儿子表中, 年龄<=20 的对象, le(less equals)不止一个
List<Son> son_list6 = sonDao.queryBuilder().where(SonDao.Properties.年龄.ge(20)).list();
//查询 儿子表中, 年龄 <20的 对象, lt(less than), 不止一个
List<Son> son_list3 = sonDao.queryBuilder().where(SonDao.Properties.年龄.lt(20)).list();
//查询 儿子表中, 年龄不等于 18的对象 ,noteq(not equal), 不止一个
List<Son> son_list4 = sonDao.queryBuilder().where(SonDao.Properties.年龄.noteq(18)).list();
//单表多重条件
//查询 表中,姓名类似于 Luc , 并且年龄<= 24岁的 女生,按 身高从大到小(orderAsc)排序,从小到大(orderDesc)
List<Studenter> person_list = studenterDao.queryBuilder().where(StudenterDao.Properties.姓名.like("Luc")
,StudenterDao.Properties.年龄.le(24),StudenterDao.Properties.性别.eq("女"))
.orderAsc(StudenterDao.Properties.身高).list;
联合多个表进行查询:
Ps: 由于本人也是一个菜鸡,对于多表查询暂时没有好的解决方法,所以还参杂着原生sql,
要是有大佬会,希望帮帮小弟。
问题:有学生表(StudentTable), 课程表(CourseTable), 选课表(XuankeTable)
1.学生表有 ID(studentId),姓名(studentName),性别(studentSex),年龄(studentAge).
2.课程表有 ID(courseId),课程名(courseName).
3.选课表有 学生ID(studentId),课程ID(courseId).
问:查询 选修了 aotoman(凹头曼) 课程 ,小于20岁 的女学生姓名?
学生表:(id是Long类型, 名字、性别是String类型,年龄是Long类型)
课程表:(id是Long类型 ,课程名是 String类型)
选课表:(第一个是学生id,Long类型,第二个是这个学生所选课程的id,Long类型):
关键代码:
List<StudentTable> studenttables_list = studentTableDao.queryBuilder()
.where(new WhereCondition.StringCondition("STUDENT_ID IN " +
"(SELECT STUDENT_ID FROM XUANKE_TABLE WHERE COURSE_ID IN " +
"(SELECT COURSE_ID FROM COURSE_TABLE WHERE COURSE_NAME='aotoman'))"),
StudentTableDao.Properties.StudentSex.eq("woman"),
StudentTableDao.Properties.StudentAge.lt(20)).list();
接下来就是具体的完整过程:
有一个界面如下:
1.按钮下方是个 listview,用于显示数据库内容
2.有3个存入按钮,在上方输入相关的值,点第一个按钮是将数据存入学生表(注意学生表四个edittext都要填,而课程表,选课表只要填前两个edittext),点第二个按钮将数据存入课程表,点第三个按钮,将数据存入选课表。
3.点击查询是在下方处显示内容。
一、添加依赖,生成相关代码(详细操作网上有)
myclass.java
package com.ilikelxystill.greendaolibrary;
import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Property;
import de.greenrobot.daogenerator.Schema;
public class MyClass {
public static void main(String[] args){
//声明建表, 第一个参数是版本号,第二个参数是生成的代码所在包名,应当填app里的用于放数据库的包
Schema schema = new Schema(1,"database_package");
Entity StudentTable = schema.addEntity("StudentTable");
StudentTable.addLongProperty("studentId").primaryKey();
StudentTable.addStringProperty("studentName");
StudentTable.addStringProperty("studentSex");
StudentTable.addLongProperty("studentAge");
Entity CourseTable = schema.addEntity("CourseTable");
CourseTable.addLongProperty("courseId").primaryKey();
CourseTable.addStringProperty("courseName");
Entity XuankeTable = schema.addEntity("XuankeTable");
XuankeTable.addLongProperty("studentId");
XuankeTable.addLongProperty("courseId");
//运行此程序,即可在指定位置生成代码
try {
new DaoGenerator().generateAll(schema,"app/src/main/java");
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行后,就会在指定包名生成8个 文件
为了 ListView更好显示相关信息,我们要重写 StudentTable.java这个类的toString方法,
我们打开这个类,加上下面这个方法:
public String toString(){
return getStudentId()+" "+getStudentName()+"\n"+getStudentSex()+"\n"+getStudentAge();
}
二、 MainActivity.java
package com.ilikelxystill.fuxi;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Iterator;
import java.util.List;
import database_package.CourseTable;
import database_package.CourseTableDao;
import database_package.DaoMaster;
import database_package.DaoSession;
import database_package.Student;
import database_package.StudentTable;
import database_package.StudentTableDao;
import database_package.XuankeTable;
import database_package.XuankeTableDao;
import de.greenrobot.dao.query.WhereCondition;
public class selectDuliActivity extends AppCompatActivity {
//xml控件的声明
private EditText edit1,edit2,edit3,edit4;
private Button cunqu_button1,cunqu_button2,cunqu_button3,select_button;
private ListView listview_here;
//适配器的声明
private ArrayAdapter<StudentTable> arrayAdapter;
//数据库, DaoMaster,DaoSession的声明
private SQLiteDatabase sq_database;
private DaoMaster master;
private DaoSession session;
//多表查询
private StudentTableDao studentTableDao;
private CourseTableDao courseTableDao;
private XuankeTableDao xuankeTableDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_duli);
init_all();
init_database();
mouseclickevent();
}
//初始化函数
public void init_all(){
edit1=(EditText)findViewById(R.id.edit1);
edit2=(EditText)findViewById(R.id.edit2);
edit3=(EditText)findViewById(R.id.edit3);
edit4=(EditText)findViewById(R.id.edit4);
cunqu_button1 = (Button)findViewById(R.id.cunqu_button1);
cunqu_button2 = (Button)findViewById(R.id.cunqu_button2);
cunqu_button3 = (Button)findViewById(R.id.cunqu_button3);
select_button = (Button)findViewById(R.id.select_button);
listview_here = (ListView)findViewById(R.id.listview_here);
arrayAdapter = new ArrayAdapter<StudentTable>(this,R.layout.list_cell);
}
//建立一个可读写的数据库
public void init_database(){
sq_database = new DaoMaster.DevOpenHelper(selectDuliActivity.this,
"xuanke.db",null).getWritableDatabase();
//实例化master,绑定指定的数据库,实例化与master相关的session
master = new DaoMaster(sq_database);
session = master.newSession();
studentTableDao = session.getStudentTableDao();
courseTableDao = session.getCourseTableDao();
xuankeTableDao = session.getXuankeTableDao();
}
//往数据库中添加学生 元素
public void addStudent(long c_id,String c_name,String c_sex,long c_age){
StudentTable studentTable1 = new StudentTable();
studentTable1.setStudentId(c_id);
studentTable1.setStudentName(c_name);
studentTable1.setStudentSex(c_sex);
studentTable1.setStudentAge(c_age);
studentTableDao.insert(studentTable1);
}
//往数据库中添加课程 元素
public void addCourse(long c_id,String c_name){
CourseTable courseTable1 = new CourseTable();
courseTable1.setCourseId(c_id);
courseTable1.setCourseName(c_name);
courseTableDao.insert(courseTable1);
}
//往数据库中添加选课内容 元素
public void addXuanke(long c_studentid,long c_courseid){
XuankeTable xuankeTable1 = new XuankeTable();
xuankeTable1.setStudentId(c_studentid);
xuankeTable1.setCourseId(c_courseid);
xuankeTableDao.insert(xuankeTable1);
}
//字符转化为数字
public long zhuanhua(String c_str){
return Long.valueOf(c_str);
}
//鼠标点击事件处理汇总
public void mouseclickevent(){
//存取 学生元素的点击事件
cunqu_button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//获取edittext中的内容
String getedit1 = edit1.getText().toString();
String getedit2 = edit2.getText().toString();
String getedit3 = edit3.getText().toString();
String getedit4 = edit4.getText().toString();
if(!getedit1.equals("")&&!getedit2.equals("")&&!getedit3.equals("")&&!getedit4.equals("")){
long changestudentid = zhuanhua(getedit1);
long changestudentage = zhuanhua(getedit4);
addStudent(changestudentid,getedit2,getedit3,changestudentage);
Toast.makeText(selectDuliActivity.this,"已存入数据库!",Toast.LENGTH_SHORT).show();
edit1.setText(null);
edit2.setText(null);
edit3.setText(null);
edit4.setText(null);
}else{
Toast.makeText(selectDuliActivity.this,"数据非法!",Toast.LENGTH_SHORT).show();
}
}
});
//存取 课程元素 的点击事件
cunqu_button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String getedit1 = edit1.getText().toString();
String getedit2 = edit2.getText().toString();
if(!getedit1.equals("")&&!getedit2.equals("")){
long changecourseid = zhuanhua(getedit1);
addCourse(changecourseid,getedit2);
Toast.makeText(selectDuliActivity.this,"已存入数据库!",Toast.LENGTH_SHORT).show();
edit1.setText(null);
edit2.setText(null);
edit3.setText(null);
edit4.setText(null);
}else{
Toast.makeText(selectDuliActivity.this,"数据非法!",Toast.LENGTH_SHORT).show();
}
}
});
//存取 选课元素 的点击事件
cunqu_button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String getedit1 = edit1.getText().toString();
String getedit2 = edit2.getText().toString();
if(!getedit1.equals("")&&!getedit2.equals("")){
long changestudentid = zhuanhua(getedit1);
long changecourseid = zhuanhua(getedit2);
addXuanke(changestudentid,changecourseid);
Toast.makeText(selectDuliActivity.this,"已存入数据库!",Toast.LENGTH_SHORT).show();
edit1.setText(null);
edit2.setText(null);
edit3.setText(null);
edit4.setText(null);
}else{
Toast.makeText(selectDuliActivity.this,"数据非法!",Toast.LENGTH_SHORT).show();
}
}
});
//查询 选修了 aotoman 课程 ,小于20岁 的女生姓名
select_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<StudentTable> studenttables_list = studentTableDao.queryBuilder()
.where(new WhereCondition.StringCondition("STUDENT_ID IN " +
"(SELECT STUDENT_ID FROM XUANKE_TABLE WHERE COURSE_ID IN " +
"(SELECT COURSE_ID FROM COURSE_TABLE WHERE COURSE_NAME='aotoman'))"),
StudentTableDao.Properties.StudentSex.eq("woman"),
StudentTableDao.Properties.StudentAge.lt(20)).list();
// List<CourseTable> studenttables_list = courseTableDao.queryBuilder().list();
// studentTableDao.deleteAll();
// List<StudentTable> studenttables_list = studentTableDao.queryBuilder().list();
// List<XuankeTable> studenttables_list = xuankeTableDao.queryBuilder().orderAsc(XuankeTableDao.Properties.StudentId).list();
Iterator<StudentTable> studentTableIterator1 = studenttables_list.iterator();
arrayAdapter.clear();
while(studentTableIterator1.hasNext()){
StudentTable studentTable1 = studentTableIterator1.next();
listview_here.setAdapter(arrayAdapter);
arrayAdapter.add(studentTable1);
}
}
});
}
}
三、activity_main.xml
```html
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".selectDuliActivity">
<EditText
android:id="@+id/edit1"
android:hint="id"
android:layout_width="match_parent"
android:layout_height="70dp" />
<EditText
android:id="@+id/edit2"
android:hint="name"
android:layout_width="match_parent"
android:layout_height="70dp" />
<EditText
android:id="@+id/edit3"
android:hint="sex"
android:layout_width="match_parent"
android:layout_height="70dp" />
<EditText
android:id="@+id/edit4"
android:hint="age"
android:layout_width="match_parent"
android:layout_height="70dp" />
<LinearLayout
android:orientation="horizontal"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="70dp">
<Button
android:id="@+id/cunqu_button1"
android:text="存入1"
android:layout_marginRight="15dp"
android:layout_width="60dp"
android:layout_height="40dp" />
<Button
android:id="@+id/cunqu_button2"
android:text="存入2"
android:layout_marginRight="15dp"
android:layout_width="60dp"
android:layout_height="40dp" />
<Button
android:id="@+id/cunqu_button3"
android:text="存入3"
android:layout_marginRight="15dp"
android:layout_width="60dp"
android:layout_height="40dp" />
<Button
android:id="@+id/select_button"
android:text="查询"
android:layout_width="60dp"
android:layout_height="40dp" />
</LinearLayout>
<ListView
android:id="@+id/listview_here"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</LinearLayout>
**四、ListView中,Adapter的格式,放在 Layout文件里**
```html
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#f5f"
android:textSize="20dp">
</TextView>
最后,运行,找出两个学生, Lucy和 lala
要是亲有不用 原生sql的方法,记得告诉我,我的qq 2569658002.