1. 程式人生 > >資料儲存之SQLite與LitePal

資料儲存之SQLite與LitePal

SQLite

一.簡意:

(1)SQLite:是一款輕量級關係資料庫,佔用資源少,執行速度快

(2)適用於大量複雜關係資料(file,sp此時不太適合)

二,用法:

(1)建立一個類 繼承SQLiteOpenHelper,重寫onCreate()和onUpgrade()方法

onCreate()方法:建立表

onUpgrade():版本更新

如下:

public class MyDatabaseHelper extends SQLiteOpenHelper {
    private Context mContext;

    //創表語句
    public static final String CREATE_BOOK = "create table Book ("
            + "id integer primary key autoincrement, "
            + "author text, "
            + "price real, "
            + "pages integer, "
            +"name text)";

    //創表語句2
    public static final String CREATE_CATEGORY = "create table Category ("
            + "id integer primary key autoincrement, "
            + "category_name text, "
            + "category_code integer)";

    public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }

    /**
     * 建立表
     * @param db
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);
        db.execSQL(CREATE_CATEGORY);
        Toast.makeText(mContext , "Create successed" , Toast.LENGTH_SHORT).show();
    }

    /**
     * 更新資料表
     * @param db
     * @param oldVersion
     * @param newVersion
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists Book");
        db.execSQL("drop table if exists Category");
        onCreate(db);
    }
}
2.在Activity中去測試:增刪改查等操作

佈局,定義簡單的幾個按鈕:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/create_database"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Create database"/>
    <Button
        android:id="@+id/add"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="add data"/>
    <Button
        android:id="@+id/delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="delete data"/>
    <Button
        android:id="@+id/update"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="update data"/>
    <Button
        android:id="@+id/retrieve"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="retrieve data"/>

</LinearLayout>

在Activity中去執行操作,

四個方法的運用說明在例子中

public class DataBaseActivity extends AppCompatActivity {

    //建立資料庫
    @ViewInject(R.id.create_database)
    private Button mBtnCreate;

    //增加資料
    @ViewInject(R.id.add)
    private Button mBtnAdd;

    //更新資料
    @ViewInject(R.id.update)
    private Button mBtnUpdate;

    //刪除資料
    @ViewInject(R.id.delete)
    private Button mBtnDelete;

    //查詢資料
    @ViewInject(R.id.retrieve)
    private Button mBtnRetrieve;

    //MyDatabaseHelper物件
    private MyDatabaseHelper dbHelper;
    //SQLiteDatabase物件
    private SQLiteDatabase db;

    private static final String TAG = "DataBaseActivity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_database);

        ViewUtils.inject(this);

        //初始化:4個引數:上下文,資料庫名字,CursorFactory物件,版本號;
        //當需要更新資料庫版本時可以+1
        dbHelper = new MyDatabaseHelper(this , "BookStore.db" , null ,1);
        db = dbHelper.getWritableDatabase();
    }


    /**
     * 建立資料庫表
     * @param view
     */
    @OnClick(R.id.create_database)
    public void CreateDatabase(View view){

        //建立或開啟一個現有的資料庫
        //getReadableDatabase():當磁碟空間滿時,將以只讀方式去開啟
        //getWritableDatabase():當磁碟已滿時,丟擲異常
        dbHelper.getWritableDatabase();
    }


    /**
     * 增加資料:public long insert(String table, String nullColumnHack, ContentValues values)
     * table:表名
     * nullColunmHack:用於在未指定新增資料時,給某些空列自動賦值null
     * values:ContentValues物件,新增相應資料
     * @param view
     */
    @OnClick(R.id.add)
    public void addDate(View view){

        ContentValues values = new ContentValues();
        //
        values.put("name" , "第一行程式碼");
        values.put("author" , "郭霖");
        values.put("pages" , 570);
        values.put("price" , 79.00);

        db.insert("Book" , null , values);
        values.clear();

        //
        values.put("name" , "編譯原理");
        values.put("author" ,"MouMou");
        values.put("pages" , 500);
        values.put("price" , 66.00);
        db.insert("Book" , null , values);
    }


    /**
     * 更新資料:4個引數
     * 假如突然打折,更新某個商品價格
     * public int update(String table, ContentValues values, String whereClause, String[] whereArgs)
     * whereClause:約束某些行
     * whereArgs:約束某些行的更新資料
     * @param view
     */
    @OnClick(R.id.update)
    public void updateData(View view){

        ContentValues values = new ContentValues();
        values.put("price" , 58.99);
        db.update("Book" , values , "name = ?",new String[]{"編譯原理"});

    }

    /**
     * 刪除資料:4個引數
     * public int delete(String table, String whereClause, String[] whereArgs)
     * 與update類似
     * @param view
     */
    @OnClick(R.id.delete)
    public void deleteData(View view){

        db.delete("Book" , "price < ?" ,new  String[]{"60"});
    }


    /**
     * 查詢資料:7個引數
     *     public Cursor query(String table, String[] columns, String selection,
     * String[] selectionArgs, String groupBy, String having,
     * String orderBy)
     * table--查詢的表名,columns--指定要查詢的列名(select column1,column2...)
     * selection ---- 指定where的約束條件(where column = value)
     * selectionArgs---為where中的佔位符提供具體值
     * groupBy  --- 指定需要group by 的列(group by column)
     * having -- 對group by後的結果進行約束(having column = value)
     * orderBy    指定查詢結果的排序方式(order by column1,column2,,,)
     * @param view
     */
    @OnClick(R.id.retrieve)
    public void retrieveData(View view){

        Cursor cursor = db.query("Book" , null ,null, null ,null , null ,null);
        if(cursor.moveToFirst()){
            do{
                String name = cursor.getString(cursor.getColumnIndex("name"));
                String author = cursor.getString(cursor.getColumnIndex("author"));
                int pages = cursor.getInt(cursor.getColumnIndex("pages"));
                double price = cursor.getDouble(cursor.getColumnIndex("price"));

                Log.d(TAG , "book name is " + name);
                Log.d(TAG , "book author is " + author);
                Log.d(TAG , "book pages is " + pages);
                Log.d(TAG , "book price is " + price);

            }while (cursor.moveToNext());

        }//if
        cursor.close();
    }
}
現在基本操作就這樣了,

記得自己去看SQLiteDatabase和SQLiteOpenHelper的原始碼略....


LitePal:

這是github上的開源庫,穩定性強,操作簡單,效率高等等

運用:

(1)在build.gradle(app)新增依賴:

compile 'org.litepal.android:core:1.5.1'
(2)在app/src/main下新建一個路徑命名:assets,然後在該目錄下建立xml檔案litepal.xml

內容如下:

<?xml version="1.0" encoding="utf-8" ?>
<litepal>

<!--資料庫名字.db-->
<dbname value = "BookStore"/>

<!--資料庫版本,更新時改動版本-->
<version value = "1"/>

<!--這是自己新建的用於資料庫存放表資料型別-->
<list>
    <mapping class = "testsdcard.cai.maiyu.mdaima06_01.bean.Book"/>
</list>
</litepal>

無疑是指定資料庫名字,版本,還有一個後面你自己建立的資料表型別(可以先不新增)

(3)在manifest中去配置:

在<application   

android:name="org.litepal.LitePalApplication"
.....

>

......

</application>

若是用自己的application也一樣,記得在自己定義的application的onCreate方法中初始化:LitePal 。初始化(this);

(4)建立資料表類:繼承DataSupport

public class Book extends DataSupport{
    private int id;     //id
    private String name;    //書名
    private String author;  //作者
    private int pages;      //頁數
    private double price;   //價格
  //  private String press; //出版社

//    public String getPress() {
//        return press;
//    }
//
//    public void setPress(String press) {
//        this.press = press;
//    }

    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 getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public int getPages() {
        return pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

(5)Activity中使用:
public class TestLitePalActivity extends AppCompatActivity {

    //建立資料庫
    @ViewInject(R.id.create_database)
    private Button mBtnCreate;

    //增加資料
    @ViewInject(R.id.add)
    private Button mBtnAdd;

    //更新資料
    @ViewInject(R.id.update)
    private Button mBtnUpdate;

    //刪除資料
    @ViewInject(R.id.delete)
    private Button mBtnDelete;

    //查詢資料
    @ViewInject(R.id.retrieve)
    private Button mBtnRetrieve;

    private static final String TAG = "TestLitePalActivity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_database);

        ViewUtils.inject(this);

    }

    //建立資料庫
    @OnClick(R.id.create_database)
    public void createDatabase(View view){


        //獲取資料庫
        LitePal.getDatabase();
    }

    /**
     * 新增資料
     * @param view
     */
    @OnClick(R.id.add)
    public void addData(View view){

        Book book = new Book();
        book.setName("大話資料結構");
        book.setAuthor("程傑");
        book.setPages(516);
        book.setPrice(43.00);
        //book.setPress("Unknow");//增加出版社
        book.save();
    }


    /**
     * 刪除資料
     * @param view
     */
    @OnClick(R.id.delete)
    public void deleteData(View view){

        DataSupport.deleteAll(Book.class , "price < ?" , "60");

    }

    /**
     * 更新資料
     * @param view
     */
    @OnClick(R.id.update)
    public void updateData(View view){

        Book book = new Book();
        book.setPrice(38.50);
        book.updateAll("name = ? and author = ?" , "大話資料結構" , "程傑");
//更新資料為預設值
//        book.setToDefault("pages");
//        book.updateAll();
    }

    /**
     * 查詢資料
     * @param view
     */
    @OnClick(R.id.retrieve)
    public void retrieveData(View view){

        List<Book> books = DataSupport.findAll(Book.class);
        for(Book book : books){
            Log.d(TAG , "book name is " + book.getName());
            Log.d(TAG , "book author is " + book.getAuthor());
            Log.d(TAG , "book pages is " + book.getPages());
            Log.d(TAG , "book price is " + book.getPrice());

        }


        //(2)新增限制:select--選定哪幾列
        //where--約束條件,   order--結果排序 ,limit---結果的數量
        //offset---查詢結果的便宜了offset(1)代表查詢表中的從第2條開始
//        List<Book> books = DataSupport.select("name" , "author" ,"pages")
//                .where("pages > ?" , "600")
//                .order("pages")
//                .limit(10)
//                .offset(10)
//                .find(Book.class);
        //(3)用原生資料庫語句查詢
//        Cursor cursor = DataSupport.findBySQL("select * from Book where pages > ?" +
//                " and price < ?" ,"700" ,"60");

    }
}

從程式碼中,對比SQLite,發現更簡單,更方便,是不是呢?

(1)建立,更新,刪除,增加,是不是更方便呢,

(2)而版本更新,只需要在litepal.xml中改版本號

(3)查詢,之前要7個引數,現在利用DataSupport.findXXX就可以了

(4)記得建立資料表類要繼承DataSupport類

(5)查詢還支援多種查詢,原生SQL語句查詢,

。。。最後去看一下原始碼

相關推薦

資料儲存SQLiteLitePal

SQLite 一.簡意: (1)SQLite:是一款輕量級關係資料庫,佔用資源少,執行速度快 (2)適用於大量複雜關係資料(file,sp此時不太適合) 二,用法: (1)建立一個類 繼承SQLiteOpenHelper,重寫onCreate()和onUpgrade()方法

Android 資料儲存 SQLite資料庫儲存

轉載自:https://www.cnblogs.com/woider/p/5136734.html ----------------------------------------SQLite資料庫---------------------------------------------- SQLite是一

Android資料儲存SQLite簡單用法

實現效果圖如下: activity_main.xml佈局檔案 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/a

IOS 資料儲存 SQLite詳解

// ViewController.m // JRSQLite查詢3 // // Created by jerehedu on 15/6/16. // Copyright (c) 2015年 jerehedu. All rights reserved. // #import "Vi

資料儲存SQLite

dbHelper.java package com.terry; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; i

Android資料儲存Sqlite採用SQLCipher資料庫加密實戰

前言:   最近研究了Android Sqlite資料庫(文章地址:http://www.cnblogs.com/whoislcj/p/5506294.html)以及ContentProvider程式間資料共享(http://www.cnblogs.com/whoislcj/p/5507928.html),

MySQL資料型別BLOBTEXT及其最大儲存限制

https://blog.csdn.net/q3dxdx/article/details/51014357 BLOB,二進位制大物件(位元組流)。可以用來儲存圖片,聲音和視訊等二進位制檔案。沒有字符集的說法。 TEXT,文字大物件(字元流)

Android資料儲存(3)SQLite簡介和簡單的登入註冊原始碼

操作SQLite資料的基本操作步驟: Android群:239123204 (在此不考慮用SQLiteOpenHelper類)  1.獲取SQLiteDatabase物件db建立資料庫或連線資料庫:SQLiteDatabasedb = SQLiteDatabase.op

Android系列SQLiteAndroid Studio的資料互動

一、把db放在res的下方創一個raw資料夾,裡面用來放db 二、創一個DbHelper類,實際程式碼如下: public class DbHelper extends SQLiteOpenHelper{ /** *

資料型別Integerint

資料型別之Integer與int Java入門  基本資料型別 眾所周知,Java是面向物件的語言,一切皆物件。但是為了相容人類根深蒂固的資料處理習慣,加快常規資料的處理速度,提供了9種基本資料型別,他們都不

js資料存貯陣列json

1 陣列:var arr=new array()或者是var arr=[ ];其中arr是物件  可以定義var a=[],或者var b=[] 都可以 陣列物件為[13,25,65,89]  如果我們要取出89這個數,那麼 arr[3]就是89 陣列是用下標來表示的,下標是從0開始;

Python資料結構: 棧佇列

棧(stacks) 是一種只能通過訪問其一端來實現資料儲存與檢索的線性資料結構,具有後進先出(last in first out,LIFO)的特徵 stack = [] stack.append("A") #A入棧 stack.append("B") #B入棧 st

Excel資料管理排序分類彙總視訊課程

課程目標要使製作或設計的工作表更加具有可讀和容易分析,可以通過一些常用的管理來實現,包括排序、分類彙總和篩選等。本課程將介紹相關的知識和技巧。適用人群電腦愛好者、所有職場人士 本課程章節計劃表: 第一章 概述、最快速且最簡單的排序方法第二章 按行進行排序第三章 按單元格顏色進行排序第四章 多條件排序第五章

原創 | 入門資料分析--資料儲存常用資料庫及區別

獲取資料,除了通過外部獲得,內部獲取,也是一個主要獲取資料的方式。內部資料主要是通過資料庫儲存的方式,將資料存下來,便於各個需求方再去提取應用。那麼,企業常用的儲存資料的資料庫都有哪些呢?不同的資料庫的儲存區別又有哪些? 目前市場上的資料庫主要可以分為關係型資料庫和非關係型資料庫,關係型資料庫通過外來鍵關聯

資料儲存使用MongoDB資料庫儲存資料

安裝MongoDB環境: 1.官網下載:https://www.mongodb.com/download-center#community 2.MongoDB視覺化工具compass下載https://www.mongodb.com/download-center#compass 筆記

android的資料儲存(3)(LitePal)

在上一章的SQLiteDatebase來操作資料庫好用嗎?不同的人有不同的答案,接下來你將接觸一個開源庫LitePal,它採用了物件關係對映的(ORM)的模式,並將我們平常用到的資料庫功能進行封裝,使用一行sql語句就可以完成各種建表和增刪改查的操作。   一、配置LitePal

那些年,我爬過的北科(五)——資料儲存使用MongoDB

介紹 在前面我們介紹瞭如何編寫爬蟲,但是我們的爬蟲並沒有把資料儲存下來,只是簡單的顯示在控制檯中。在本節,我們將簡單學習一下資料庫,以及如何在python中操作資料庫。 最後,我們將修改上一節的爬蟲框架,使其支援資料庫插入。 注:如果讀者已經瞭解mongodb,可以直接跳到最後一個部分:修改我們的爬蟲框

HTML5--資料儲存計算器【加減】

<!DOCTYPE html> <html>     <head>         <meta charset="UTF-8">         <title>計算器</title>         &l

python資料儲存列表:一些注意的地方

1.常用列表的列表推導式 a = [i for i in range(n)]  # 會生成關於i的一個列表,其中可以對i進行判斷篩選,或者進行其他操作 在列表資料清洗可以使用列表推導式,例如簡單的一個列表元素資料的清洗操作 a = [1,2,3,4]   # 對列表a中的資

Flutter知識點:資料儲存sqflite

sqflite是一款輕量級的關係型資料庫,類似SQLite。 在Flutter平臺我們使用sqflite庫來同時支援Android 和iOS。 使用介紹 1.首選需要在pubspec.yaml 匯入庫