LitePal 是一款 Android 数据库框架,它采用了对象关系映射(ORM)的模式,将我们平时最常用到的一些数据库功能进行了封装,可以不用编写一行 SQL 语句就可以完成各种建表和增删改查的操作。
1,在 app/build.gradle 文件中添加如下:
compile 'org.litepal.android:core:1.6.1'
2,配置 litepal.xml 文件。右击 app/src/main 目录 → New →Directory,创建一个 assets 目录,然后在 assets 目录下再新建一个 litepal.xml 文件,接着编辑 litepal.xml 文件内容,如下:
<litepal>
<dbname value="BookStore">dbname>
<version value="1">version>
<list>
list>
litepal>
3.Configure LitePalApplication 配置LitePalApplication:在AndroidManifest.xml 中添加一句话:
"org.litepal.LitePalApplication"
...
>
...
public class Album extends DataSupport {
@Column(unique = true, defaultValue = "unknown")
private String name;
private float price;
private byte[] cover;
private List songs = new ArrayList();
// generated getters and setters.
...
}
public class Song extends DataSupport {
@Column(nullable = false)
private String name;
private int duration;
@Column(ignore = true)
private String uselessField;
private Album album;
// generated getters and setters.
...
}
2.将类添加到 litepal.xml中
<list>
<mapping class="org.litepal.litepalsample.model.Album" />
<mapping class="org.litepal.litepalsample.model.Song" />
list>
3.创建表
case R.id.main_create_btn:
SQLiteDatabase db = LitePal.getDatabase();
break;
case R.id.add_album_btn:
String albumName = albumEt.getText().toString();
float price = 109.9f;
Album album = new Album();
album.setName(albumName);
album.setPrice(price);
album.save();//保存至数据库
break;
case R.id.update_btn:
Album albumToUpdate = DataSupport.find(Album.class, 11);
albumToUpdate.setPrice(20.99f); // raise the price
albumToUpdate.save();
Toast.makeText(MainActivity.this,"更新成功",Toast.LENGTH_SHORT).show();
break;
case R.id.delete_album_btn:
int row=DataSupport.delete(Album.class,2);
int row=DataSupport.deleteAll(Album.class,"id>?","3");
Toast.makeText(this,"您删除了"+row+"行数据",Toast.LENGTH_SHORT).show();
break;
case R.id.query_album_btn:
List albumList=DataSupport.findAll(Album.class);
List albumList = DataSupport.where("id and name like ?", "9", "a%").order("name").find(Album.class);