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

大家在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:

 1 package com.my.bean;
 2 
 3 import com.j256.ormlite.field.DatabaseField;
 4 import com.j256.ormlite.table.DatabaseTable;
 5 
 6 
 7 
 8 
 9 @DatabaseTable(tableName="tb_users")
10 public class Users {
11     @DatabaseField(generatedId=true)
12     private int id;
13     @DatabaseField(columnName="name")
14     private String name;
15     @DatabaseField(columnName="desc")
16     private String desc;
17     public int getId() {
18         return id;
19     }
20     public void setId(int id) {
21         this.id = id;
22     }
23     public String getName() {
24         return name;
25     }
26     public void setName(String name) {
27         this.name = name;
28     }
29     public String getDesc() {
30         return desc;
31     }
32     public void setDesc(String desc) {
33         this.desc = desc;
34     }
35     public Users( String name, String desc) {
36         super();
37         this.name = name;
38         this.desc = desc;
39     }
40     public Users() {
41         super();
42         // TODO Auto-generated constructor stub
43     }
44     
45     
46     
47 }

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

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

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

3、编写DAO类

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

DatabaseHelper:

 1 package com.my.db;
 2 
 3 import java.sql.SQLException;
 4 
 5 import android.content.Context;
 6 import android.database.sqlite.SQLiteDatabase;
 7 
 8 import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
 9 import com.j256.ormlite.dao.Dao;
10 import com.j256.ormlite.support.ConnectionSource;
11 import com.j256.ormlite.table.TableUtils;
12 import com.my.bean.Users;
13 
14 
15 public class DatabaseHelper extends OrmLiteSqliteOpenHelper{
16     private static final String TABLE_NAME = "users.db";
17     /**
18      * usersDao,每张表对应一个
19      */
20     private Dao<Users,Integer> usersDao ;
21     
22     private static DatabaseHelper instance;
23     public DatabaseHelper(Context context) {
24         super(context, TABLE_NAME, null, 1);
25         // TODO Auto-generated constructor stub
26     }
27 
28     @Override
29     public void onCreate(SQLiteDatabase arg0, ConnectionSource arg1) {
30         // TODO Auto-generated method stub
31         try{
32             TableUtils.createTable(arg1, Users.class);
33         }catch(Exception e){
34             e.printStackTrace();
35         }
36     }
37 
38     @Override
39     public void onUpgrade(SQLiteDatabase arg0, ConnectionSource arg1, int arg2,
40             int arg3) {
41         try  
42         {  
43             TableUtils.dropTable(connectionSource, Users.class, true);  
44             onCreate(arg0, connectionSource);  
45         } catch (SQLException e)  
46         {  
47             e.printStackTrace();  
48         }  
49         
50     }
51     /**
52      * 单例获取该Helper
53      */
54     public static synchronized DatabaseHelper getHelper(Context context){
55         if(instance == null){
56             synchronized (DatabaseHelper.class) {
57                 if(instance == null){
58                     instance = new DatabaseHelper(context);
59                 }
60             }
61         }
62         return instance;
63     }
64     
65     /**
66      * 获得userDao
67      * @throws SQLException 
68      */
69     public Dao<Users,Integer> getUsersDao() throws SQLException{
70         if(usersDao == null){
71             usersDao = getDao(Users.class);
72         }
73         return usersDao;
74     }
75 
76     
77     /**
78      * 释放资源
79      */
80     
81     @Override
82     public void close() {
83         // TODO Auto-generated method stub
84         super.close();
85         usersDao = null;
86     }
87 }

这里我们需要继承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);
    }
}

运行结果如下:

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

原文地址:https://www.cnblogs.com/liangshijie/p/6123487.html