当前位置: 首页 > 工具软件 > LBase-Android > 使用案例 >

Android基础之LitePal数据库 | 带源码

郭德惠
2023-12-01

LitePal

简介

  • 是一款开源的Android数据库框架,采用了对象关系映射(ORM)的模式(将面向对象语言和面向关系数据库建立一种映射关系)

配置

dbname configure the database name of project.

version configure the version of database. Each time you want to upgrade database, plus the value here.

list configure the mapping classes.

storage configure where the database file should be stored. internal and external are the only valid options.

  • 第一步在app/build.gradle中添加
implementation 'org.litepal.guolindev:core:3.2.1'
  • 第二步,在main下面创建assets目录,然后新建一个litepal.xml文件
<litepal>
		    <!--
		    	Define the database name of your application.
		    	By default each database name should be end with .db.
		    	If you didn't name your database end with .db,
		    	LitePal would plus the suffix automatically for you.
		    	For example:
		    	<dbname value="demo" />
		    -->
		    <dbname value="BookStore" />

		    <!--
		    	Define the version of your database. Each time you want
		    	to upgrade your database, the version tag would helps.
		    	Modify the models you defined in the mapping tag, and just
		    	make the version value plus one, the upgrade of database
		    	will be processed automatically without concern.
					For example:
		    	<version value="1" />
		    -->
		    <version value="1" />

		    <!--
		    	Define your models in the list with mapping tag, LitePal will
		    	create tables for each mapping class. The supported fields
		    	defined in models will be mapped into columns.
		    	For example:
		    	<list>
		    		<mapping class="com.test.model.Reader" />
		    		<mapping class="com.test.model.Magazine" />
		    	</list>
		    -->
		    <list>
		    </list>

		    <!--
		        Define where the .db file should be. "internal" means the .db file
		        will be stored in the database folder of internal storage which no
		        one can access. "external" means the .db file will be stored in the
		        path to the directory on the primary external storage device where
		        the application can place persistent files it owns which everyone
		        can access. "internal" will act as default.
		        For example:
		        <storage value="external" />
		    -->

</litepal>
  • 第三步,修改Manifest.xml文件
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    		package="com.example.litepaltest">

		    <application
		        android:name="org.litepal.LitePalApplication"
		        android:allowBackup="true"
		        android:icon="@mipmap/ic_launcher"
		        android:label="@string/app_name"
		        android:roundIcon="@mipmap/ic_launcher_round"
		        android:supportsRtl="true"
		        android:theme="@style/AppTheme">

		        <activity android:name=".MainActivity">
		            <intent-filter>
		                <action android:name="android.intent.action.MAIN" />

		                <category android:name="android.intent.category.LAUNCHER" />
		            </intent-filter>
		        </activity>
		    </application>

</manifest>

创建数据库

  • 首先定义一个Book类
public class Book extends LitePalSupport {

    @Column(nullable = false)
    private String author;

    @Column(index = true)
    private double price;

    private int pages;

    @Column(unique = true,defaultValue = "unknown")
    private String name;

    public String getAuthor() {
        return author;
    }

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

    public double getPrice() {
        return price;
    }

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

    public int getPages() {
        return pages;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
  • 修改litepal.xml的代码

使用mapping标签来声明我们要配置的映射模型类,注意一定要使用完整的类名

<list>
	  <mapping class = "com.example.litepaltest.data.Book"></mapping>
</list>
  • 修改xml
<Button
	        android:id="@+id/create_database"
	        android:layout_width="260dp"
	        android:layout_height="51dp"
	        android:text="@string/create_database"
	        android:onClick="createDatabase"
	        app:layout_constraintBottom_toBottomOf="parent"
	        app:layout_constraintEnd_toEndOf="parent"
	        app:layout_constraintHorizontal_bias="0.496"
	        app:layout_constraintStart_toStartOf="parent"
	        app:layout_constraintTop_toTopOf="parent"
	        app:layout_constraintVertical_bias="0.244" />
  • 修改MainActivity中的代码
public void createDatabase(View view) {
        
    LitePal.getDatabase();

}
  • 使用adb shell查看
CREATE TABLE android_metadata (locale TEXT);
CREATE TABLE table_schema (id integer primary key autoincrement,name text, type integer);
CREATE TABLE sqlite_sequence(name,seq);
CREATE TABLE book (id integer primary key autoincrement,pages integer, author text not null, price real, nam
		e text unique default 'unknown');
CREATE INDEX book_price_index on book (price);

升级数据库

  • 修改Book
private String press;

public String getPress() {
    return press;
}

public void setPress(String press) {
    this.press = press;
}
  • 新建Category类
public class Category extends LitePalSupport {

    @Column(defaultValue = "unknown")
    private String categoryName;

    private int categoryCode;

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public int getCategoryCode() {
        return categoryCode;
    }

    public void setCategoryCode(int categoryCode) {
        this.categoryCode = categoryCode;
    }
}
  • 修改litepal
<version value="2" />

<list>
	  <mapping class="com.example.litepaltest.data.Book"></mapping>
	  <mapping class="com.example.litepaltest.data.Category"></mapping>
</list>
  • 查看
CREATE TABLE book (id integer primary key autoincrement,pages integer, author text not null, price real, name text unique default 'unknown', press text);
CREATE INDEX book_price_index on book (price);
CREATE TABLE category (id integer primary key autoincrement,categorycode integer, categoryname text default 'unknown');

添加数据

  • 修改xml
<Button
	        android:id="@+id/add_database"
	        android:layout_width="260dp"
	        android:layout_height="51dp"
	        android:layout_marginTop="50dp"
	        android:onClick="addDatabase"
	        android:text="@string/add_database"
	        app:layout_constraintBottom_toBottomOf="parent"
	        app:layout_constraintEnd_toEndOf="parent"
	        app:layout_constraintHorizontal_bias="0.496"
	        app:layout_constraintStart_toStartOf="parent"
	        app:layout_constraintTop_toBottomOf="@+id/create_database"
	        app:layout_constraintVertical_bias="0.046" />
  • 修改MainActivity
public void addDatabase(View view) {

    Book book = new Book();
    book.setName("The Da Vinci Code");
    book.setAuthor("Dan Brown");
    book.setPages(454);
    book.setPrice(19.69);
    book.setPress("Unknown");
    book.save();

}
  • 查询
select * from book;
1|454|Dan Brown|19.69|The Da Vinci Code|Unknown

更新数据

  • xml
<Button
	        android:id="@+id/update_database"
	        android:layout_width="260dp"
	        android:layout_height="51dp"
	        android:onClick="updateDatabase"
	        android:text="@string/update_database"
	        app:layout_constraintBottom_toBottomOf="parent"
	        app:layout_constraintEnd_toEndOf="parent"
	        app:layout_constraintHorizontal_bias="0.496"
	        app:layout_constraintStart_toStartOf="parent"
	        app:layout_constraintTop_toBottomOf="@+id/add_database"
	        app:layout_constraintVertical_bias="0.067" />
  • MainActivity
public void updateDatabase(View view) {

    Book book = new Book();

    //第一种方式
    book.setName("The Lost Symbol");
    book.setAuthor("Dan Brown");
    book.setPages(510);
    book.setPrice(19.95);
    book.setPress("Unknown");
    book.save();
    book.setPrice(20.25);
    book.save();
    book.clearSavedState();

    //第二种方式
    Book book1 = LitePal.find(Book.class,1);
    book1.setPrice(18.88);
    book1.save();

    //第三种方式
    Book book2 = new Book();
    book2.setPrice(28.88);
    book2.update(1);
    book2.updateAll("name = ? and author = ?","The Lost Symbol","Dan Brown");

    //第四种方式,值设置成默认值
    Book book3 = new Book();
    book3.setToDefault("pages");
    book3.updateAll();

}

删除数据

  • xml
<Button
	        android:id="@+id/delete_database"
	        android:layout_width="260dp"
	        android:layout_height="51dp"
	        android:onClick="deleteDatabase"
	        android:text="@string/delete_database"
	        app:layout_constraintBottom_toBottomOf="parent"
	        app:layout_constraintEnd_toEndOf="parent"
	        app:layout_constraintHorizontal_bias="0.496"
	        app:layout_constraintStart_toStartOf="parent"
	        app:layout_constraintTop_toBottomOf="@+id/update_database"
	        app:layout_constraintVertical_bias="0.089" />
  • MainActivity
public void deleteDatabase(View view) {

    //第一种方式
    LitePal.delete(Book.class,2);

    //第二种方式
    LitePal.deleteAll(Book.class,"id = ?","2");

}

查询数据

  • xml
<Button
	        android:id="@+id/query_database"
	        android:layout_width="260dp"
	        android:layout_height="51dp"
	        android:onClick="queryDatabase"
	        android:text="@string/query_database"
	        app:layout_constraintBottom_toBottomOf="parent"
	        app:layout_constraintEnd_toEndOf="parent"
	        app:layout_constraintHorizontal_bias="0.496"
	        app:layout_constraintStart_toStartOf="parent"
	        app:layout_constraintTop_toBottomOf="@+id/delete_database"
	        app:layout_constraintVertical_bias="0.128" />
  • MainActivity
public void queryDatabase(View view) {

    //第一种方式
    List<Book> books = LitePal.findAll(Book.class);
    for (Book book: books) {
        Log.d("MainActivity","book name is " + book.getName());
        Log.d("MainActivity","book Author is " + book.getAuthor());
        Log.d("MainActivity","book pages is " + book.getPages());
        Log.d("MainActivity","book price is " + book.getPrice());
        Log.d("MainActivity","book press is " + book.getPress());
    }

    //第二种方式
    Book book = LitePal.find(Book.class,1);
    Log.d("MainActivity","book name is " + book.getName());
    Log.d("MainActivity","book Author is " + book.getAuthor());
    Log.d("MainActivity","book pages is " + book.getPages());
    Log.d("MainActivity","book price is " + book.getPrice());
    Log.d("MainActivity","book press is " + book.getPress());

    //第三种方式
    List<Book> books1 = LitePal.where("author = ?","Dan Brown").order("price").find(Book.class);
    for (Book book1: books1) {
        Log.d("MainActivity","book name is " + book1.getName());
        Log.d("MainActivity","book Author is " + book1.getAuthor());
        Log.d("MainActivity","book pages is " + book1.getPages());
        Log.d("MainActivity","book price is " + book1.getPrice());
        Log.d("MainActivity","book press is " + book1.getPress());
    }
}

下载地址

https://github.com/qricis/DoSomeAndroidTest/tree/main/LitePalTest

 类似资料: