1.加载相关JAR包
ormlite-android-4.48.jar及ormlite-core-4.48.jar
2.实体类注解
实体类,表名:@DatabaseTable(tableName="t_user")
主键(自增):@DatabaseField(generatedId=true)
属性(字段名):@DatabaseField(columnName="uname")
package com.example.ormliteuse.entity;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName="t_student")
public class Student {
@DatabaseField(generatedId=true)
private int studentid;
@DatabaseField
private String studentname;
@DatabaseField
private int sudentnumber;
public int getStudentid() {
return studentid;
}
public void setStudentid(int studentid) {
this.studentid = studentid;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public int getSudentnumber() {
return sudentnumber;
}
public void setSudentnumber(int sudentnumber) {
this.sudentnumber = sudentnumber;
}
public Student(int studentid, String studentname, int sudentnumber) {
super();
this.studentid = studentid;
this.studentname = studentname;
this.sudentnumber = sudentnumber;
}
public Student() {
super();
}
@Override
public String toString() {
return "Student [studentid:" + studentid + ", studentname:"
+ studentname + ", sudentnumber:" + sudentnumber + "]";
}
}
3.数据库工具类(建库,建表)
3.1继承OrmLiteSqliteOpenHelper
3.2重写onCreate 及onUpgrade 方法用于创建和更新数据库
3.3其他相关方法
package com.example.ormliteuse.util;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
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;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
public class DataBaseHelper extends OrmLiteSqliteOpenHelper {
// 存放用来操作数据库对象的集合
private Map<String, Dao> daoMap = new HashMap<String, Dao>();
// 单例模式
private static DataBaseHelper instance;
private Class dataClass;
// 私有化构造方法,只允许本类内部访问
private DataBaseHelper(Context context, String databaseName,int databaseVerson,Class dataClass) {
super(context, databaseName, null, databaseVerson);
this.dataClass=dataClass;
}
// 单例方法,提供公有化方法让外部对该类的实例对象进行访问
public static DataBaseHelper getHelper(Context context,String databaseName,int databaseVerson,Class dataClass) {
synchronized (DataBaseHelper.class) {
if (instance == null) {
instance = new DataBaseHelper(context, databaseName, databaseVerson, dataClass);
}
return instance;
}
}
/**
* 根据实体类注解产生对应的表
*/
@Override
public void onCreate(SQLiteDatabase arg0, ConnectionSource cs) {
try {
TableUtils.createTable(cs,dataClass);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase arg0, ConnectionSource arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
/**
* 通过类对象访问集合得到对应的dao对象
* @param c 类
* @return 相应的dao层
* @throws SQLException
*/
public Dao getMyDao(Class c)throws SQLException{
Dao dao=null;
String className=c.getSimpleName();
//如果集合中存在对应key的dao对象,则从集合中直接获取
if (daoMap.containsKey(className)) {
dao=daoMap.get(className);
}
//类似单例模式
if (dao==null) {
//如果集合中不存在对应名称的dao对象,实例化该集合对象
dao=super.getDao(c);
daoMap.put(className, dao);
}
return dao;
}
/**
* 关闭资源
*/
@Override
public void close() {
super.close();
for (String key : daoMap.keySet()) {
Dao dao=daoMap.get(key);
dao=null;
}
}
}
4.数据库CRUD相关方法
4.1添加create(对象)
4.2查询全部queryForAll()
4.3更新用户update(对象)
4.4根据ID删除deleteById(id编号)
4.5根据ID查询queryForId(id编号)
package com.example.ormliteuse.dao;
import java.util.List;
import com.example.ormliteuse.entity.Student;
public interface StudentDao {
/**
* 添加学生
* @param student
* @return
*/
public boolean addStudent(Student student);
/**
* 删除学生
* @param student
* @return
*/
public boolean deleteStudent(Student student);
/**
* 修改学生
* @param student
* @return
*/
public boolean updateStudent(Student student);
/**
* 查询所有学生
* @return
*/
public List<Student> findAllStudent();
/**
* 根据id查询学生
* @param id
* @return
*/
public Student findStudentById(int id);
}
<pre class="java" name="code">package com.example.ormliteuse.constant;
public class Constant {
public static final String DATABASE_NAME="OrmLiteUse.db";
public static final int DATABASE_VERSON=1;
}
package com.example.ormliteuse.dao.imp;
import java.sql.SQLException;
import java.util.List;
import android.content.Context;
import com.example.ormliteuse.constant.Constant;
import com.example.ormliteuse.dao.StudentDao;
import com.example.ormliteuse.entity.Student;
import com.example.ormliteuse.util.DataBaseHelper;
import com.j256.ormlite.dao.Dao;
public class StudentDaoImp implements StudentDao{
private Dao<Student,Integer> dao;
private Context context;
public StudentDaoImp(Context context){
try {
this.dao=DataBaseHelper.getHelper(context, Constant.DATABASE_NAME, Constant.DATABASE_VERSON, Student.class).getMyDao(Student.class);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean addStudent(Student student) {
int i=0;
try {
i=dao.create(student);
if (i>0) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
@Override
public boolean deleteStudent(Student student) {
int i=0;
try {
i=dao.deleteById(student.getStudentid());
if (i>0) {
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
@Override
public boolean updateStudent(Student student) {
int i=0;
try {
i=dao.update(student);
if (i>0) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
@Override
public List<Student> findAllStudent() {
try {
return dao.queryForAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
public Student findStudentById(int id) {
try {
return dao.queryForId(id);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="@dimen/activity_vertical_margin"
android:layout_marginLeft="@dimen/activity_horizontal_margin"
android:layout_marginRight="@dimen/activity_horizontal_margin"
android:layout_marginTop="@dimen/activity_vertical_margin"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/main_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="学生表"
android:textSize="30dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/activity_vertical_margin" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="编号:"
android:textSize="20dp" />
<EditText
android:id="@+id/main_id"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/activity_vertical_margin" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="学号:"
android:textSize="20dp" />
<EditText
android:id="@+id/main_number"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/activity_vertical_margin" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名:"
android:textSize="20dp" />
<EditText
android:id="@+id/main_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/activity_vertical_margin"
android:orientation="horizontal" >
<Button
android:id="@+id/main_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="增"
android:textSize="20dp" />
<Button
android:id="@+id/main_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="删"
android:textSize="20dp" />
<Button
android:id="@+id/main_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="改"
android:textSize="20dp" />
<Button
android:id="@+id/main_find"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="查"
android:textSize="20dp" />
</LinearLayout>
</LinearLayout>
package com.example.ormliteuse;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.ormliteuse.dao.StudentDao;
import com.example.ormliteuse.dao.imp.StudentDaoImp;
import com.example.ormliteuse.entity.Student;
public class MainActivity extends Activity implements OnClickListener {
private EditText nameEt, numberEt, idEt;
private Button addBtn, deleteBtn, updateBtn, findBtn;
private StudentDao dao;
private String name;
private int number, id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameEt = (EditText) findViewById(R.id.main_name);
numberEt = (EditText) findViewById(R.id.main_number);
idEt = (EditText) findViewById(R.id.main_id);
addBtn = (Button) findViewById(R.id.main_add);
deleteBtn = (Button) findViewById(R.id.main_delete);
updateBtn = (Button) findViewById(R.id.main_update);
findBtn = (Button) findViewById(R.id.main_find);
addBtn.setOnClickListener(this);
deleteBtn.setOnClickListener(this);
updateBtn.setOnClickListener(this);
findBtn.setOnClickListener(this);
dao = new StudentDaoImp(MainActivity.this);
}
@Override
public void onClick(View v) {
Student student = new Student();
switch (v.getId()) {
case R.id.main_add:
try {
name = nameEt.getText().toString().trim();
number = Integer.parseInt(numberEt.getText().toString().trim());
student.setStudentname(name);
student.setSudentnumber(number);
if (dao.addStudent(student)) {
Toast.makeText(MainActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
}
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "请输入正确学号", Toast.LENGTH_SHORT).show();
}
break;
case R.id.main_delete:
try {
id = Integer.parseInt(idEt.getText().toString().trim());
student.setStudentid(id);
if (dao.deleteStudent(student)) {
Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
}
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "请输入正确id", Toast.LENGTH_SHORT).show();
}
break;
case R.id.main_update:
name = nameEt.getText().toString();
try {
id = Integer.parseInt(idEt.getText().toString().trim());
if (dao.findStudentById(id) == null) {
Toast.makeText(MainActivity.this, "不存在该编号的学生", Toast.LENGTH_SHORT).show();
} else {
student = dao.findStudentById(id);
if (name.equals("") && numberEt.getText().toString().trim().equals("")) {
Toast.makeText(MainActivity.this, "请输入要修改的学号或姓名", Toast.LENGTH_SHORT).show();
} else if (name.equals("") || numberEt.getText().toString().trim().equals("")) {
if (name.equals("")) {
try {
number = Integer.parseInt(numberEt.getText().toString().trim());
student.setSudentnumber(number);
if (dao.updateStudent(student)) {
Toast.makeText(MainActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
}
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "请输入正确学号", Toast.LENGTH_SHORT).show();
}
} else {
student.setStudentname(name);
if (dao.updateStudent(student)) {
Toast.makeText(MainActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
}
}
} else {
try {
number = Integer.parseInt(numberEt.getText().toString().trim());
student.setSudentnumber(number);
student.setStudentname(name);
if (dao.updateStudent(student)) {
Toast.makeText(MainActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
}
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "请输入正确学号", Toast.LENGTH_SHORT).show();
}
}
}
} catch (NumberFormatException e1) {
Toast.makeText(MainActivity.this, "请输入正确的id", Toast.LENGTH_SHORT).show();
}
break;
case R.id.main_find:
try {
if (idEt.getText().toString().trim().equals("")) {
String str = "";
for (Student key : dao.findAllStudent()) {
str += key.toString();
}
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
} else {
id = Integer.parseInt(idEt.getText().toString().trim());
if (dao.findStudentById(id) != null) {
Toast.makeText(MainActivity.this, dao.findStudentById(id).toString(), Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(MainActivity.this, "不存在该编号的学生", Toast.LENGTH_SHORT).show();
}
}
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "请输入正确id", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
public void judgeNumberByFind(String str, int number) {
int number1 = 0;
try {
number1 = Integer.parseInt(str);
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "请输入正确数字", Toast.LENGTH_SHORT).show();
}
if (number1 > 0) {
number = number1;
if (dao.findStudentById(number) != null) {
Toast.makeText(MainActivity.this, dao.findStudentById(number).toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "不存在该编号的学生", Toast.LENGTH_SHORT).show();
}
}
}
}
效果图: