OrmLite的简单使用--建表和查询员工信息

本文详细介绍了使用OrmLite进行数据库操作的步骤,包括导入jar包、创建实体类、管理类,以及具体代码实现,适用于不同版本的OrmLite。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我在网上找OrmLite的教程时遇到了很多问题,花了好大劲才解决的。这里简单的介绍一下OrmLite的使用。

主要步骤

1、导入jar包(高版本和低版本有些操作不一样)
2、创建实体类(表)
3、创建帮助类,也叫管理类

一、导入jar包

下载ormlite包,官网下载地址:https://ormlite.com/releases/

(常见的有1.9.x和5.x.x版本,实体类的注释方法与jar包版本相关,网上有两大类的注释方法,缘于此)

在这里插入图片描述
将jar包复制粘贴到project目录下的libs文件下,右键jar文件,点击Add As Library…,弹出窗口后点击OK;当jar文件可以点开时就成功了。
在这里插入图片描述
成功后的样子:
在这里插入图片描述
二、创建实体类

根据表的属性及约束条件,添加类属性及对应注释即可。注释的具体含义及用法可以找相关资料。网上有两大类的注释使用方法:
jar低版本:

@Table("table_name")
public class Stuff{
    @PrimaryKey(.....)
    private int id;
    ......
}

jar高版本:

@DatabaseTable(tableName = "staff")
public class Staff {

    @DatabaseField(......)
    private int id;
}

实体类Staff代码:(最好要有个空构造函数及全属性的get、set函数)

package com.example.lab5exam03;

import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;


@DatabaseTable(tableName = "staff")
public class Staff {

    @DatabaseField(columnName = "id", dataType = DataType.INTEGER, id = true)
    private int id;
    @DatabaseField(columnName = "name", dataType = DataType.STRING, canBeNull = false)
    private String name;
    @DatabaseField(columnName = "sex", dataType = DataType.STRING, canBeNull = false)
    private String sex;
    @DatabaseField(columnName = "department", dataType = DataType.STRING, canBeNull = false)
    private String department;
    @DatabaseField(columnName = "salary", dataType = DataType.FLOAT, canBeNull = false)
    private  float salary;

    Staff(){

    }

    Staff(int id, String name, String sex, String department, float salary){
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.department = department;
        this.salary = salary;
    }

    public String getAllMessage(){
        return id+"\t"+name+"\t"+sex+"\t"+department+"\t"+salary;
    }
    public int getId() {
        return id;
    }

    public float getSalary() {
        return salary;
    }

    public String getDepartment() {
        return department;
    }

    public String getSex() {
        return sex;
    }

    public String getName() {
        return name;
    }

    public void setSalary(float salary) {
        this.salary = salary;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

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

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

三、创建帮助类

帮助类要继承OrmLiteSqliteOpenHelper类
调用Dao类的Dao方法可以简化操作,Dao概念了解一下就行

帮助类能简化我们操作数据库的难度,其中Dao类很重要,Dao自带许多对数据库的操作方法,编写代码时直接调用就行。Dao的具体使用网上简单查阅一下,就基本会用了。Dao数据库查询操作要多注意一下。

帮助类DataBaseHelper的代码:

package com.example.lab5exam03;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

//要继承OrmLiteSqliteOpenHelper帮助类
public class DataBaseHelper extends OrmLiteSqliteOpenHelper {
    //数据库的名字
    private static final String DBNAME = "test.db";
    //数据库版本
    private static final int version = 1;
    //Dao类,简化数据库的增删改查等操作
    private Dao<Staff, Integer> staffDao;

    public Dao<Staff, Integer> getStaffDao() {
        if (staffDao == null) {
            try {
                staffDao = getDao(Staff.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return staffDao;
    }

    DataBaseHelper(Context context) {
        //创建数据库
        //上下文,数据库名字,工厂(一般为空),版本
        super(context, DBNAME, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
            //创建staff表
            TableUtils.createTableIfNotExists(connectionSource, Staff.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        //用于升级数据库,内容可为空
    }
    //==============下面的是数据库的相关操作,通过调用Dao自带的方法就能完成对数据库的操作=============
    //==============具体的Dao方法网上有,常用:xx.delete(class)/xx.deleteById(int)=================
    //==============xx.0000(class)  xx.ooooById(int)   xx.ooooAll()
    //增
    public void addStaff(Staff staff) {
        try {
            staffDao.create(staff);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删
    public void deleteStaff(Staff staff) {
        try {
            staffDao.delete(staff);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //改
    public void updateStaff(Staff staff) {
        try {
            staffDao.update(staff);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //查
    public String selectStaffById(Integer id) {
        try {
           return (staffDao.queryForId(id)).getAllMessage();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "无该员工";
    }
}

四、事件类代码

package com.example.lab5exam03;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.j256.ormlite.dao.Dao;


public class MainActivity extends AppCompatActivity {

    private DataBaseHelper dbhelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化数据
        initData();


        Button button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText editText = (EditText)findViewById(R.id.editText);
                int id = Integer.parseInt(editText.getText().toString());
                String msg =  dbhelper.selectStaffById(id);
                TextView result = (TextView)findViewById(R.id.result);
                result.setText("查询结果\n"+msg);
            }
        });

    }
    private void initData(){
        dbhelper = new DataBaseHelper(this);
        Dao<Staff,Integer> staffdao = dbhelper.getStaffDao();

        Staff staff1 = new Staff(1,"小明","男","员工",4000);
        dbhelper.addStaff(staff1);

        Staff staff2 = new Staff(2,"小红","女","员工",4500);
        dbhelper.addStaff(staff2);

        Staff staff3 = new Staff(3,"小强","男","员工",5000);
        dbhelper.addStaff(staff2);


    }


}


XML布局代码

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/员工信息" />

        <EditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName" />

        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/add" />

        <TextView
            android:id="@+id/result"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="@string/table" />

    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

strings.xml代码:

<resources>
    <string name="app_name">Lab5Exam03</string>
    <string name="员工信息">输入要查询的员工编号:</string>
    <string name="add">查询</string>
    <string name="table">查询结果:\n</string>
</resources>

结果截图
在这里插入图片描述在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值