OrmLite可以帮助我们将会数据库操作,不用自己去写SQL语句,而且设置它跟使用Sqlite一样的方式,它是一种关系型数据,我比较喜欢的就是它能够帮助我判断数据表项是更新还是创建等操作,不需要自己去写大量的SQL语句去判断,下面介绍一下它的使用文档以及一些基本的注意点:
官方网址:http://ormlite.com/
JavaDOC地址:http://ormlite.com/javadoc/ormlite-android/
开发文档地址:http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite.html
一、建立模型
首先创建一个Model,作为一个数据表,在Android中我使用的是实现Parcelable,代码如下:
package com.jwzhangjie.capricorntv.bean;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import android.os.Parcel;
import android.os.Parcelable;
/**
*
* @author zj 包含视频的参数 视频的名字 "channel_id":9, "channel_name":"湖南卫视",
* "icon_url":"http://tv.togic.com:8080/ShowTimeService/images/182.png",
* "province":"湖南", "mode":"SD", "url":
* "http://live.gslb.letv.com/gslb?stream_id=hunan&tag=live&ext=m3u8&sign=live_tv&platid=10&splatid=1012&temporarykey=db7c39a0ee39ab2d4d2e781d5"
* ,
* "second_url":["http://live-cdn.kksmg.com/channels/tvie/test/flv:500k"
* ,
* "http://live.gslb.letv.com/gslb?stream_id=hunanHD_1800&tag=live&ext=m3u8&sign=live_tv&platid=10&splatid=1012&temporarykey=db7c39a0ee39ab2d4d2e781d5"
* ,
* "http://pplive.shntv.cn/live/5/30/e9301e073cf94732a380b765c8b9573d.m3u8?type=ipad"
* ,"rtsp://rlive.tv189.cn/live/112"], "types":"2|0"
*/
public class LiveItemBean implements Parcelable {
@Override
public int describeContents() {
return 0;
}
public LiveItemBean() {
}
private LiveItemBean(Parcel source) {
readFromParcel(source);
}
@DatabaseField(id = true)
private int channel_id;
@DatabaseField
private String channel_name;
@DatabaseField
private String icon_url;
@DatabaseField
private String province;
@DatabaseField
private String mode;
@DatabaseField
private String url;
@DatabaseField
private String second_urls;
private String[] second_url;
@DatabaseField
private String types;
private void readFromParcel(Parcel source) {
channel_name = source.readString();
icon_url = source.readString();
province = source.readString();
mode = source.readString();
url = source.readString();
second_urls = source.readString();
second_url = (String[]) source.readArray(LiveItemBean.class
.getClassLoader());
types = source.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(channel_id);
dest.writeString(channel_name);
dest.writeString(icon_url);
dest.writeString(province);
dest.writeString(mode);
dest.writeString(url);
dest.writeString(second_urls);
dest.writeArray(second_url);
dest.writeString(types);
}
public static Creator<LiveItemBean> CREATOR = new Creator<LiveItemBean>() {
@Override
public LiveItemBean createFromParcel(Parcel source) {
return new LiveItemBean(source);
}
@Override
public LiveItemBean[] newArray(int size) {
return new LiveItemBean[size];
}
};
public int getChannel_id() {
return channel_id;
}
public void setChannel_id(int channel_id) {
this.channel_id = channel_id;
}
public String getChannel_name() {
return channel_name;
}
public void setChannel_name(String channel_name) {
this.channel_name = channel_name;
}
public String getIcon_url() {
return icon_url;
}
public void setIcon_url(String icon_url) {
this.icon_url = icon_url;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getSecond_urls() {
return second_urls;
}
public void setSecond_urls(String second_urls) {
this.second_urls = second_urls;
}
public String[] getSecond_url() {
return second_url;
}
public void setSecond_url(String[] second_url) {
this.second_url = second_url;
StringBuffer buffer = new StringBuffer();
int count = second_url.length;
for (int i = 0; i < count; i++) {
buffer.append(second_url[i]);
if (i != count-1) {
buffer.append(";");
}
}
second_urls = buffer.toString();
}
public String getTypes() {
return types;
}
public void setTypes(String types) {
this.types = types;
}
}
我们分析上面的代码同时介绍一下与之相关的配置:
1、是类名,这里我使用的数据表的名字是默认类的小写,当然你还可以指定表名字,使用@DatabaseTable(tableName = "liveitembeans"),
2、主键,在上面的代码中有一行@DatabaseField(id = true)被注解对象就是主键,当然我们有时候使用的一个自增长的id,我们可以设置为@DatabaseField(generatedId = true)来实现,当然还有很多其他的注解配置我这里就不一一说明了,自己可以到官网可以查看找到自己需要的。
二、创建DBHelper
package com.jwzhangjie.capricorntv.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.jwzhangjie.capricorntv.bean.LiveItemBean;
public class DBHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_NAME = "jwzhangjie.db";
private static final int DATABASE_VERSION = 1;
public DBHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase,
ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, LiveItemBean.class);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase,
ConnectionSource connectionSource, int oldVer, int newVer) {
try {
TableUtils.dropTable(connectionSource, LiveItemBean.class, true);
onCreate(sqLiteDatabase, connectionSource);
} catch (Exception e) {
e.printStackTrace();
}
}
}
上面使用TableUtils来创建和删除表,还有其他的功能例如清空表内容等
三、创建操作工具
接下来就是创建一个操作数据库的工具DAO
package com.jwzhangjie.capricorntv.uitls;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import com.j256.ormlite.dao.Dao;
import com.jwzhangjie.capricorntv.bean.LiveItemBean;
import com.jwzhangjie.capricorntv.db.DBHelper;
public class DBUtils {
public static Dao<LiveItemBean, Integer> liveDao = null;
public DBUtils(Context context) {
if (liveDao == null) {
DBHelper dbHelper = new DBHelper(context);
try {
liveDao = dbHelper.getDao(LiveItemBean.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 插入直播数据,如果数据存在则进行更新
*
* @param liveItemBean
*/
public void LiveCreate(LiveItemBean liveItemBean) {
try {
liveDao.createOrUpdate(liveItemBean);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 连续进行插入,如果存在则更新
*/
public void LiveCreates(List<LiveItemBean> lists) {
try {
for (LiveItemBean liveItemBean : lists) {
liveDao.createOrUpdate(liveItemBean);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 查询所有的直播元素
* @return
*/
public List<LiveItemBean> getLiveItemBeans(){
List<LiveItemBean> listsBeans = new ArrayList<LiveItemBean>();
try {
listsBeans = liveDao.queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
return listsBeans;
}
}
上面实现了创建和查询,在上面的有一个连续插入多个数据,还可以使用OrmLite提供的批处理任务方法如下:
/**
* 连续进行插入,如果存在则更新
*/
public void LiveCreates(final List<LiveItemBean> lists) {
try {
liveDao.callBatchTasks(new Callable<Void>() {
@Override
public Void call() throws Exception {
for (LiveItemBean liveItemBean : lists) {
liveDao.createOrUpdate(liveItemBean);
}
return null;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
查询除了用已有的接口,我们还可以使用sql语句来实现,比如:
// find out how many orders account-id #10 has
GenericRawResults<String[]> rawResults =
orderDao.queryRaw(
"select count(*) from orders where account_id = 10");
// there should be 1 result
List<String[]> results = rawResults.getResults();
// the results array should have 1 value
String[] resultArray = results.get(0);
// this should print the number of orders that have this account-id
System.out.println("Account-id 10 has " + resultArray[0] + " orders");
四、最后释放
当我们应用退出时候,我们需要释放之前对象
OpenHelperManager.releaseHelper();
dbHelper = null;