Android—Ormlite框架简单的操作数据库

时间:2022-05-25 22:48:11

大家在Android项目中或多或少的都会使用数据库,为了提高我们的开发效率,当然少不了数据库ORM框架了,尤其是某些数据库操作特别频繁的app;本篇博客将详细介绍ORMLite的简易用法。

下面开始介绍ORMLite的入门用法~

1、下载 ORMLite Jar

首先去ORMLite官网下载jar包,对于Android为:ormlite-android-5.0.jar 和 ormlite-core-5.0.jar ;

ps:访问不了的朋友,文章末尾会把jar、源码、doc与本篇博客例子一起打包提供给大家下载。

2、配置Bean类

有了jar,我们直接新建一个项目为:OrmliteDemo,然后把jar拷贝到libs下。

然后新建一个包:com.my.bean专门用于存放项目中的Bean,首先新建一个Usera.Java

Users:

 package com.my.bean;

 import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable; @DatabaseTable(tableName="tb_users")
public class Users {
@DatabaseField(generatedId=true)
private int id;
@DatabaseField(columnName="name")
private String name;
@DatabaseField(columnName="desc")
private String desc;
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 getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Users( String name, String desc) {
super();
this.name = name;
this.desc = desc;
}
public Users() {
super();
// TODO Auto-generated constructor stub
} }

首先在User类上添加@DatabaseTable(tableName = "tb_user"),标明这是数据库中的一张表,标明为tb_users

然后分别在属性上添加@DatabaseField(columnName = "name") ,columnName的值为该字段在数据中的列名

@DatabaseField(generatedId = true) ,generatedId 表示id为主键且自动生成

3、编写DAO类

原生的数据库操作,需要继承SQLiteOpenHelper,这里我们需要继承OrmLiteSqliteOpenHelper

DatabaseHelper:

 package com.my.db;

 import java.sql.SQLException;

 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;
import com.my.bean.Users; public class DatabaseHelper extends OrmLiteSqliteOpenHelper{
private static final String TABLE_NAME = "users.db";
/**
* usersDao,每张表对应一个
*/
private Dao<Users,Integer> usersDao ; private static DatabaseHelper instance;
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
// TODO Auto-generated constructor stub
} @Override
public void onCreate(SQLiteDatabase arg0, ConnectionSource arg1) {
// TODO Auto-generated method stub
try{
TableUtils.createTable(arg1, Users.class);
}catch(Exception e){
e.printStackTrace();
}
} @Override
public void onUpgrade(SQLiteDatabase arg0, ConnectionSource arg1, int arg2,
int arg3) {
try
{
TableUtils.dropTable(connectionSource, Users.class, true);
onCreate(arg0, connectionSource);
} catch (SQLException e)
{
e.printStackTrace();
} }
/**
* 单例获取该Helper
*/
public static synchronized DatabaseHelper getHelper(Context context){
if(instance == null){
synchronized (DatabaseHelper.class) {
if(instance == null){
instance = new DatabaseHelper(context);
}
}
}
return instance;
} /**
* 获得userDao
* @throws SQLException
*/
public Dao<Users,Integer> getUsersDao() throws SQLException{
if(usersDao == null){
usersDao = getDao(Users.class);
}
return usersDao;
} /**
* 释放资源
*/ @Override
public void close() {
// TODO Auto-generated method stub
super.close();
usersDao = null;
}
}

这里我们需要继承OrmLiteSqliteOpenHelper,其实就是间接继承了SQLiteOpenHelper

然后需要实现两个方法:

1、onCreate(SQLiteDatabase database,ConnectionSource connectionSource)

创建表,我们直接使用ormlite提供的TableUtils.createTable(connectionSource, User.class);进行创建~

2、onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion)

更新表,使用ormlite提供的TableUtils.dropTable(connectionSource, User.class, true);进行删除操作~

删除完成后,别忘了,创建操作:onCreate(database, connectionSource);

然后使用单例公布出一个创建实例的方法,getHelper用于获取我们的help实例;

4、显示在Activity

  MainActivity:

package com.example.ormlitedemo;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView; import com.j256.ormlite.dao.Dao;
import com.my.bean.Users;
import com.my.db.DatabaseHelper; public class MainActivity extends Activity {
private Dao<Users,Integer> usersDao;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
//新建一个表格布局
TableLayout tblay = new TableLayout(this);
//给该Activity设置布局
setContentView(tblay,new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
//插入数据
init();
try{ //取出数据
List<Users> users = getList(); //遍历集合
for (Users u : users) {
//创建一行
TableRow tr = new TableRow(this);
//新建文本视图
TextView v1 = new TextView(this);
TextView v2 = new TextView(this);
TextView v3 = new TextView(this);
v1.setText(u.getId()+"");
v2.setText(u.getName());
v3.setText(u.getDesc());
//把文本视图添加到TableRow中
tr.addView(v1,new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1));
tr.addView(v2,new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1));
tr.addView(v3,new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1));
//把TableRow添加到TableLayout中
tblay.addView(tr);
} }catch(Exception e){
e.printStackTrace();
}
}
//插入数据
public void init(){
DatabaseHelper helper = DatabaseHelper.getHelper(context);
try{
Users u1 = new Users("zhy","2b铅笔");
usersDao = helper.getUsersDao();
usersDao.create(u1);
u1 = new Users("zhy2", "2b铅笔");
usersDao.create(u1);
u1 = new Users("zhy3", "2b铅笔");
usersDao.create(u1);
u1 = new Users("zhy4", "2b铅笔");
usersDao.create(u1);
u1 = new Users("zhy5", "2b铅笔");
usersDao.create(u1);
u1 = new Users("zhy6", "2b铅笔");
usersDao.create(u1);
}catch(Exception e){
e.printStackTrace();
}
}
//查询所有操作
public List<Users> getList(){
DatabaseHelper helper = DatabaseHelper.getHelper(context);
List<Users> users = null;
try{
users = helper.getUsersDao().queryForAll(); }catch(Exception e){
e.printStackTrace();
}
return users;
} //删除操作
public void DeleteUser(){
DatabaseHelper helper = DatabaseHelper.getHelper(context);
try{
helper.getUsersDao().deleteById(2);
}catch(Exception e){
e.printStackTrace();
}
}
//更新操作
public void UpdateUser(){
DatabaseHelper helper = DatabaseHelper.getHelper(context);
try{
Users u1 = new Users("lisi", "4b铅笔");
u1.setId(3);
helper.getUsersDao().update(u1);
}catch(Exception e){
e.printStackTrace();
} } @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

运行结果如下:

Android—Ormlite框架简单的操作数据库

好了,Ormlite的简单操作就说这里了。。。。希望对大家有用,不喜勿喷