数据库之OrmLite的简单学习:增删改查_两个表

参考学习网址:

1.android OrmLite 入门 - ziqiang1的专栏 - CSDN博客 http://blog.csdn.net/ziqiang1/article/details/52121643
2.android OrmLite 实际应用 - ziqiang1的专栏 - CSDN博客 http://blog.csdn.net/ziqiang1/article/details/52131304
3.Android ORMLite 框架的入门用法 - Hongyang - CSDN博客 http://blog.csdn.net/lmj623565791/article/details/39121377
综合学习了这个帖子,大概了解了OrmLite的增删改查。

核心步骤:

1.下载需要的jar包:
OrmLite Releases - Lightweight Object Relational Mapping (ORM) http://ormlite.com/releases/
具体做法根据android OrmLite 入门 - ziqiang1的专栏 - CSDN博客 http://blog.csdn.net/ziqiang1/article/details/52121643

2.具体代码实现根据android OrmLite 实际应用 - ziqiang1的专栏 - CSDN博客 http://blog.csdn.net/ziqiang1/article/details/52131304

以下是我学习别人的贴纸之后的代码

1.布局:

<?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:gravity="center|top"
    android:orientation="vertical">

    <EditText
        android:id="@+id/ed_text"
        android:hint="请输入id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"/>
    <TextView
        android:id="@+id/tv_add_info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:text="增学生、班级"/>
    <TextView
        android:id="@+id/tv_delete_info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:text="删学生byId"/>
    <TextView
        android:id="@+id/tv_delete_info_class"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:text="删班级byId"/>
    <TextView
        android:id="@+id/tv_update_info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:text="改学生byId"/>
    <TextView
        android:id="@+id/tv_search_info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:text="查学生byId"/>
    <TextView
        android:id="@+id/tv_search_all_info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:text="查所有学生、班级"/>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/tv_show_result"
            android:layout_marginTop="15dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="21sp"
            android:text="显示操作结果"/>
    </ScrollView>

</LinearLayout>

2.BaseDao:

public abstract class BaseDao<T,ID> {

    private DatabaseHelper helper;

    public BaseDao(Context context){
        helper = DatabaseHelper.getInstance( context);
    }

    public DatabaseHelper getHelper(){
        return helper;
    }

    public abstract Dao<T,ID> getDao();

    public int add(T t){
        try {
            return getDao().create( t);
        }catch ( SQLException e){
            e.printStackTrace();
        }
        return -1;
    }

    public int addList(List<T> list){
        try {
            return getDao().create( list);
        }catch ( SQLException e){
            e.printStackTrace();
        }
        return -1;
    }

    public List<T> getAll(){
        List<T> list = new ArrayList<>();
        try {
            list = getDao().queryForAll();
        }catch ( SQLException e){
            e.printStackTrace();
        }
        return list;
    }

    public T get(ID id){
        try {
            return getDao().queryForId( id);
        }catch ( SQLException e){
            e.printStackTrace();
        }
        return null;
    }

    public int update(T t){
        try {
            return getDao().update( t);
        }catch ( SQLException e){
            e.printStackTrace();
        }
        return -1;
    }

    public int delete(ID id){
        try {
            return getDao().deleteById( id);
        }catch ( SQLException e){
            e.printStackTrace();
        }
        return -1;
    }

}

3.Classz:

@DatabaseTable( tableName = Classz.TABLE_NAME)
public class Classz {

    public final static String TABLE_NAME = "t_class";

    @DatabaseField(id = true)
    private String id;

    @DatabaseField(unique = true, canBeNull =  false)
    private String name;

    @DatabaseField( defaultValue = "音乐楼")
    private String address;


    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "classz{ id =" + id +" name=" + name +",address=" + address  +"}\n";
    }

}

4.ClasszDao:

public class ClasszDao extends BaseDao<Classz,String>{


    public ClasszDao(Context context) {
        super(context);
    }

    @Override
    public Dao<Classz, String> getDao() {
        try {
            return getHelper().getDao(Classz.class);
        }catch ( SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据班级名称获取班级信息
     * @param className
     * @return
     */
    public Classz getClassz( String className){
        try {
            List<Classz> name = getDao().queryBuilder()
                    .where().eq("name",className).query();
            if( name != null && name.size() > 0){
                return name.get( 0);
            }
        }catch ( SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

}

5.DatabaseHelper:

/**
 * 数据库和表的创建
 */

public class DatabaseHelper extends OrmLiteSqliteOpenHelper{

    private static final String TABLE_NAME = "my_orm_db";
    private static final int DB_VERSION = 1;

    private static DatabaseHelper instance;

    /**
     * 获得数据库实例
     * @param mContext
     * @return
     */
    public static DatabaseHelper getInstance( Context mContext){
        mContext = mContext.getApplicationContext();
        if( instance == null ){
            synchronized ( DatabaseHelper.class){
                if( instance == null){
                    instance = new DatabaseHelper( mContext);
                }
            }
        }
        return instance;
    }

    public DatabaseHelper(Context context){
        super( context, TABLE_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        Log.d("myorm","表开始新建");
        try {
            TableUtils.createTable( connectionSource, Student.class);
            TableUtils.createTable( connectionSource, Classz.class);
            Log.d("myorm","表创建成功");
        }catch ( SQLException e){
            Log.d("myorm","表创建失败");
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
        Log.d("myorm","更新表");

//        try {
//            // 删除旧的数据库表。
//            TableUtils.dropTable(connectionSource, Classz.class, true);
//            TableUtils.dropTable(connectionSource, Student.class, true);
//
//            // 重新创建新版的数据库。
//            onCreate(sqLiteDatabase, connectionSource);
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
        
    }

}

6.Student:

/**
 * 每一个实体类对应一张表
 * 注解说明:
 *
 * 1.@DatabaseTable
 * DatabaseTable是一个类注解,一般用在实体类的上面,被添加该注解的类会创建一张表,
 * 表名称默认为类名称的小写,我们也可以通过 tableName 来指定表名称
 *
 * 2.@DatabaseField
 * DatabaseField是一个属性注解,使用在被添加DatabaseTable注解的类中的属性字段上,
 * 被添加该注解的类字段,在表中也会有一个相对应的表字段
 *
 */

@DatabaseTable(tableName = Student.TABLE_NAME)
public class Student {

    public static final String TABLE_NAME = "t_student";

    @DatabaseField(generatedId = true)
    private int id;

    @DatabaseField(defaultValue = "玫玫")
    private String name;

    @DatabaseField( foreign = true, columnName = "ofClass", foreignAutoRefresh = true)
    private Classz ofClass;

    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 Classz getOfClass() {
        return ofClass;
    }

    public void setOfClass(Classz ofClass) {
        this.ofClass = ofClass;
    }

    @Override
    public String toString() {
        return "student{ id =" + id +" name=" + name +",ofClass=" + ofClass +"}\n";
    }
}

7.StudentDao:


public class StudentDao extends BaseDao<Student, Integer>{

    public StudentDao(Context context){
        super( context);
    }

    @Override
    public Dao<Student, Integer> getDao() {
        try {
            return getHelper().getDao( Student.class);
        }catch ( SQLException e){
            e.printStackTrace();
        }
        return null;
    }

}

8.HomeActivity:

public class HomeActivity extends AppCompatActivity {

    @BindView(R.id.ed_text)
    EditText edText;
    @BindView(R.id.tv_add_info)
    TextView tvAddInfo;
    @BindView(R.id.tv_delete_info)
    TextView tvDeleteInfo;
    @BindView(R.id.tv_update_info)
    TextView tvUpdateInfo;
    @BindView(R.id.tv_search_info)
    TextView tvSearchInfo;
    @BindView(R.id.tv_show_result)
    TextView tvShowResult;
    @BindView(R.id.tv_search_all_info)
    TextView tvSearchAllInfo;
    @BindView(R.id.tv_delete_info_class)
    TextView tvDeleteInfoClass;

    private StudentDao studentDao;
    private ClasszDao classzDao;

    private int number = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);

        studentDao = new StudentDao(HomeActivity.this);
        classzDao = new ClasszDao(HomeActivity.this);
    }


    /**
     * 向表里插入信息
     */
    public void addInfo() {

        Classz classz = new Classz();
        classz.setId(String.valueOf(number));
        classz.setName("钢琴" + number + "班");

        Student student = new Student();
        student.setOfClass(classz);
        student.setName("莉莉" + number);
        student.setId(number);

        int addStudent = studentDao.add(student);
        int addClassz = classzDao.add(classz);
        String str1 = addStudent > -1 ? "添加student成功" : "添加student失败";
        String str2 = addClassz > -1 ? "添加classz成功" : "添加classz失败";
        tvShowResult.setText(number + str1 + str2);

        number++;
    }

    /**
     * 按id来查找对象
     */
    public void queryById() {
        String str = edText.getText().toString().trim();
        if (TextUtils.isEmpty(str)) {
            return;
        }
        try {
            int i = Integer.parseInt(str);
            Student student = studentDao.get(i);
            if( student == null ){
                tvShowResult.setText("无此对象");
            }else{
                tvShowResult.setText(student.toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询表中所有对象
     */
    public void queryAll() {
        List<Student> studentAll = studentDao.getAll();
        List<Classz> classzsAll = classzDao.getAll();
        tvShowResult.setText( "student:" + studentAll.toString() + "\n---------" + "\n" + "classz:" + classzsAll.toString());
    }

    /**
     * 更新学生对象信息
     */
    public void updateInfo() {
        String str = edText.getText().toString().trim();
        if (TextUtils.isEmpty(str)) {
            return;
        }
        Student student = studentDao.get( Integer.parseInt(str));
        if( student == null){
            tvShowResult.setText("无此学生对象,转班失败");
            return;
        }
        String studentOldInfo = student.toString();
        Classz classz = classzDao.getClassz("钢琴1班");
        if( classz == null){
            tvShowResult.setText("无此班级对象,转班失败");
            return;
        }
        student.setOfClass(classz);
        int update = studentDao.update(student);
        tvShowResult.setText( "studentOldInfo:" + studentOldInfo + "\n"
                + ( update > -1 ? "转班成功" : "转班失败")  + "\n"
                +  "studentNewInfo:" +  student.toString() );
    }

    /**
     * 删除表中对象
     */
    public void deleteInfo() {
        String str = edText.getText().toString().trim();
        if (TextUtils.isEmpty(str)) {
            return;
        }
        try {
            int i = Integer.parseInt(str);
            int result = studentDao.delete(i);
            tvShowResult.setText(result > -1 ? "删除成功" : "删除失败");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除表中班级对象
     */
    public void deleteInfoClassz() {
        String str = edText.getText().toString().trim();
        if (TextUtils.isEmpty(str)) {
            return;
        }
        try {
            int result = classzDao.delete(str);
            tvShowResult.setText(result > -1 ? "删除成功" : "删除失败");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.tv_add_info, R.id.tv_delete_info, R.id.tv_update_info,
            R.id.tv_search_info, R.id.tv_search_all_info, R.id.tv_delete_info_class})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_add_info:
                addInfo();
                break;
            case R.id.tv_delete_info:
                deleteInfo();//删除学生
                break;
            case R.id.tv_delete_info_class:
                deleteInfoClassz();
                break;
            case R.id.tv_update_info:
                updateInfo();
                break;
            case R.id.tv_search_info:
                queryById();
                break;
            case R.id.tv_search_all_info:
                queryAll();
                break;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值