Android中OrmLite數據庫的使用

   換了一個項目後,需要把大量數據保存到本地,所以在選用數據庫上有了小小的糾結,比較了SQLite,GreenDao,OrmLite後決定使用一個輕量級的數據庫,說實話之前數據庫這邊用到的並不多,也就是存個登陸密碼用戶名什麼的,用Shareprefrence就足夠了。在網上看了一些資料後,決定用OrmLite這個數據庫。如果對SQL的語言不熟悉的話,使用OrmLite這個庫是很合適的。

使用起來也很方便,下面講解一下ormlite在android studio中的使用

1)在工程中導入jar包


 如圖:就是紅線標起來的這兩個,沒有的話,可以在網上搜,本章下面會給出源代碼,源碼裏也有。

2)然後在你的項目的build.gradle裏引用這兩個jar包

 compile files('libs/ormlite-android-4.48.jar')
 compile files('libs/ormlite-core-4.48.jar')

3)下面我們就可以使用這個Ormlite數據庫了,這裏以Book創建數據庫,(書名,價格,作者,類別.......),首先來看這個實體類

package printertestdemo.test.com.textormlite;

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

/**
 * Created by admin on 2017/4/11.
 */
@DatabaseTable(tableName = "BookEntity")
public class BookEntity {
    @DatabaseField(generatedId = true)//generatedId 表示id爲主鍵且自動生成
    private int id;
    @DatabaseField(columnName = "ProductCodeLevel1")
    private String ProductCodeLevel1;
    @DatabaseField(columnName = "ProductNameLevel1")
    private String ProductNameLevel1;
    @DatabaseField(columnName = "ProductCodeLevel2")
    private String ProductCodeLevel2;
    @DatabaseField(columnName = "ProductNameLevel2")
    private String ProductNameLevel2;
    @DatabaseField(columnName = "ProductCodeLevel3")
    private String ProductCodeLevel3;
    @DatabaseField(columnName = "ProductNameLevel3")
    private String ProductNameLevel3;
    @DatabaseField(columnName = "ProductCodeLevel4")
    private String ProductCodeLevel4;
    @DatabaseField(columnName = "ProductName")
    private String ProductName;
    @DatabaseField(columnName = "LeftCount")
    private String LeftCount;
    @DatabaseField(columnName = "Price")
    private String Price;
    @DatabaseField(columnName = "Agio")
    private String Agio;
    @DatabaseField(columnName = "Score")
    private String Score;
    @DatabaseField(columnName = "Intrudoction")
    private String Intrudoction;


    public BookEntity() {
    }

    public BookEntity( String productCodeLevel1, String productNameLevel1, String productCodeLevel2, String productNameLevel2, String productCodeLevel3, String productNameLevel3, String productCodeLevel4, String productName, String leftCount, String price, String agio, String score, String intrudoction) {
        ProductCodeLevel1 = productCodeLevel1;
        ProductNameLevel1 = productNameLevel1;
        ProductCodeLevel2 = productCodeLevel2;
        ProductNameLevel2 = productNameLevel2;
        ProductCodeLevel3 = productCodeLevel3;
        ProductNameLevel3 = productNameLevel3;
        ProductCodeLevel4 = productCodeLevel4;
        ProductName = productName;
        LeftCount = leftCount;
        Price = price;
        Agio = agio;
        Score = score;
        Intrudoction = intrudoction;
    }

    public int getId() {
        return id;
    }

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

    public String getProductCodeLevel1() {
        return ProductCodeLevel1;
    }

    public void setProductCodeLevel1(String productCodeLevel1) {
        ProductCodeLevel1 = productCodeLevel1;
    }

    public String getProductNameLevel1() {
        return ProductNameLevel1;
    }

    public void setProductNameLevel1(String productNameLevel1) {
        ProductNameLevel1 = productNameLevel1;
    }

    public String getProductCodeLevel2() {
        return ProductCodeLevel2;
    }

    public void setProductCodeLevel2(String productCodeLevel2) {
        ProductCodeLevel2 = productCodeLevel2;
    }

    public String getProductNameLevel2() {
        return ProductNameLevel2;
    }

    public void setProductNameLevel2(String productNameLevel2) {
        ProductNameLevel2 = productNameLevel2;
    }

    public String getProductCodeLevel3() {
        return ProductCodeLevel3;
    }

    public void setProductCodeLevel3(String productCodeLevel3) {
        ProductCodeLevel3 = productCodeLevel3;
    }

    public String getProductNameLevel3() {
        return ProductNameLevel3;
    }

    public void setProductNameLevel3(String productNameLevel3) {
        ProductNameLevel3 = productNameLevel3;
    }

    public String getProductCodeLevel4() {
        return ProductCodeLevel4;
    }

    public void setProductCodeLevel4(String productCodeLevel4) {
        ProductCodeLevel4 = productCodeLevel4;
    }

    public String getProductName() {
        return ProductName;
    }

    public void setProductName(String productName) {
        ProductName = productName;
    }

    public String getLeftCount() {
        return LeftCount;
    }

    public void setLeftCount(String leftCount) {
        LeftCount = leftCount;
    }

    public String getPrice() {
        return Price;
    }

    public void setPrice(String price) {
        Price = price;
    }

    public String getAgio() {
        return Agio;
    }

    public void setAgio(String agio) {
        Agio = agio;
    }

    public String getScore() {
        return Score;
    }

    public void setScore(String score) {
        Score = score;
    }

    public String getIntrudoction() {
        return Intrudoction;
    }

    public void setIntrudoction(String intrudoction) {
        Intrudoction = intrudoction;
    }
}
4)建庫

package printertestdemo.test.com.textormlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

/**
 * Created by admin on 2017/4/11.
 */

public class DBhelper extends OrmLiteSqliteOpenHelper {

    private static final String TABLE_NAME = "Book.db";
    private static DBhelper instance;

    public DBhelper(Context context) {
        super(context, TABLE_NAME, null, 1);

        // TODO Auto-generated constructor stub
    }

    /**
     * 單例獲取該Helper
     *
     * @param context
     * @return
     */
    public static synchronized DBhelper getHelper(Context context) {
        if (instance == null) {
            synchronized (DBhelper.class) {
                if (instance == null)
                    instance = new DBhelper(context);
            }
        }

        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase database,
                         ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, BookEntity.class);//書的實體類


            Log.d("DBhelper", "創建表成功");
        } catch (java.sql.SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase database,
                          ConnectionSource connectionSource, int oldVersion, int newVersion) {
        try {
            TableUtils.createTable(connectionSource, BookEntity.class);


        } catch (java.sql.SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        onCreate(database, connectionSource);

    }

}

現在我們就創建一個庫名爲Book.db,表名爲:BookEntity的數據庫了,每個表對應一個單獨的Dao用於操作

package printertestdemo.test.com.textormlite;

import android.content.Context;
import android.util.Log;

import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by admin on 2017/4/11.
 * 書的操作表
 */

public class BookDao {
    Context con;
    // private DBShophelps helper;
    private DBhelper helper;
    private Dao<BookEntity, Integer> personDao;

    // 構造函數
    public BookDao(Context con) {
        helper = DBhelper.getHelper(con);
        this.con = con;
    }



    // 每個表一般我們都會單獨寫個Dao用於操作
    public Dao<BookEntity, Integer> getPersonDao() throws java.sql.SQLException {
        if (personDao == null) {
            personDao = helper.getDao(BookEntity.class);
        }
        return personDao;
    }

    // 根據ID查詢
    public BookEntity selectPerson(int i) {
        try {
            BookEntity p = getPersonDao().queryForId(i);

            return p;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    // 添加某條數據---添加數據
    public void addPerson(BookEntity p) {
        try {
            getPersonDao().create(p);

        } catch (SQLException e) {
        }
    }

    // 刪除某條數據
    public void deletePerson(BookEntity p) {
        try {
            Log.d("TAG", "刪除ID爲" + p.getId() );
            getPersonDao().deleteById(p.getId());

        } catch (SQLException e) {
        }
    }

    //刪除所有數據
    public void deleteAll(List<BookEntity> listdata){

        try {
            getPersonDao().delete(listdata);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

//    // 更新某條數據
//    public void updatePerson(BookEntity p, String name) {
//        try {
//
//            p.setName(name);
//            getPersonDao().update(p);
//            Log.d("TAG", "修改數據後姓名爲:" + p.getName());
//        } catch (SQLException e) {
//        }
//    }

    // 查詢所有數據

    public List<BookEntity> showPersonAll() {
        try {
            List<BookEntity> list = getPersonDao().queryForAll();
            Log.d("2TAG", "查詢所有數據條數:" + list.size());
//            for (int i = 0; i < list.size(); i++) {
//                Log.d("2TAG", "...." + list.get(i).getName());
//            }
            return list;
        } catch (SQLException e) {
        }
        return null;
    }

    public List<BookEntity> SelectStatus(String ss,String type_id ){
        List<BookEntity> entity=null;
        try {
            entity= getPersonDao().queryForEq(ss,type_id);//字段,字段的值

            return  entity;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return  entity;
    }


}

現在這個數據庫就創建好了,怎麼用呢,你可以在你的工程的任意地方使用它,首先我們給這個表裏插入幾條數據,然後進行查詢

package printertestdemo.test.com.textormlite;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    List<BookEntity>list=new ArrayList<>();
    private Button but1,but2;
    private ListView listview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化數據
        initData();
        //數據插入成功,可以進行查詢了
         initView();//初始化控件

    }

    private void initView() {
        but1= (Button) findViewById(R.id.button);
        but2= (Button) findViewById(R.id.button1);
        listview= (ListView) findViewById(R.id.listview);
        final ListViewAdapter adapter=new ListViewAdapter(this);
        listview.setAdapter(adapter);
        final BookDao dao=new BookDao(this);
        but1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //查詢所有數據
                List<BookEntity> list1=dao.showPersonAll();
                if(list1.size()!=0){
                    adapter.clearDeviceList();
                    adapter.setDeviceList(list1);
                }
            }
        });

        but2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //查詢ProductNameLevel2爲小說的
                List<BookEntity> list1=dao.SelectStatus("ProductNameLevel2","小說");
                if(list1.size()!=0){
                    adapter.clearDeviceList();
                    adapter.setDeviceList(list1);
                }
            }
        });

    }

    private void initData() {
        //這裏我就存入五個
        BookEntity book1=new BookEntity("1","書籍","1","小說","1","言情","11111111","我愛的人","10","100","0.8","5","XXXYYYY");
        list.add(book1);
        BookEntity book2=new BookEntity("1","書籍","1","小說","2","懸疑","1121122","破案專輯","10","200","0.9","5","XXXYYYY");
        list.add(book2);
        BookEntity book3=new BookEntity("1","書籍","1","小說","3","歷史","1131133","近代歷史","10","150","0.8","5","XXXYYYY");
        list.add(book3);
        BookEntity book4=new BookEntity("1","書籍","2","工具書","1","字典","1211214","新華字典","10","10","0.9","5","XXXYYYY");
        list.add(book4);
        BookEntity book5=new BookEntity("1","書籍","2","工具書","2","生活百科","1211225","百科全書","10","80","0.7","5","XXXYYYY");
        list.add(book5);
        //向Book.db裏插入數據
        BookDao dao=new BookDao(this);
        for(BookEntity entity:list){
            dao.addPerson(entity);
        }
    }
}

Ormlite在android中使用起來非常簡單,它的數據庫的默認路徑是在data/data/包名下,這個路徑有的設備可以查看到,有的需要root後纔可以查看。此外有興趣的朋友可以看一下greendao數據庫的使用

下面給出該項目的源碼下載地址,有需要的可以下載一下看看,有什麼不足,請及時@我,大家一起進步

http://download.csdn.net/detail/shihuiyun/9813965


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章