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,代码如下:
- <spanstyle="font-size:14px;">packagecom.jwzhangjie.capricorntv.bean;
- importcom.j256.ormlite.field.DatabaseField;
- importcom.j256.ormlite.table.DatabaseTable;
- importandroid.os.Parcel;
- importandroid.os.Parcelable;
- /**
- *
- *@authorzj包含视频的参数视频的名字"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"
- */
- publicclassLiveItemBeanimplementsParcelable{
- @Override
- publicintdescribeContents(){
- return0;
- }
- publicLiveItemBean(){
- }
- privateLiveItemBean(Parcelsource){
- readFromParcel(source);
- }
- @DatabaseField(id=true)
- privateintchannel_id;
- @DatabaseField
- privateStringchannel_name;
- @DatabaseField
- privateStringicon_url;
- @DatabaseField
- privateStringprovince;
- @DatabaseField
- privateStringmode;
- @DatabaseField
- privateStringurl;
- @DatabaseField
- privateStringsecond_urls;
- privateString[]second_url;
- @DatabaseField
- privateStringtypes;
- privatevoidreadFromParcel(Parcelsource){
- 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
- publicvoidwriteToParcel(Parceldest,intflags){
- 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);
- }
- publicstaticCreator<LiveItemBean>CREATOR=newCreator<LiveItemBean>(){
- @Override
- publicLiveItemBeancreateFromParcel(Parcelsource){
- returnnewLiveItemBean(source);
- }
- @Override
- publicLiveItemBean[]newArray(intsize){
- returnnewLiveItemBean[size];
- }
- };
- publicintgetChannel_id(){
- returnchannel_id;
- }
- publicvoidsetChannel_id(intchannel_id){
- this.channel_id=channel_id;
- }
- publicStringgetChannel_name(){
- returnchannel_name;
- }
- publicvoidsetChannel_name(Stringchannel_name){
- this.channel_name=channel_name;
- }
- publicStringgetIcon_url(){
- returnicon_url;
- }
- publicvoidsetIcon_url(Stringicon_url){
- this.icon_url=icon_url;
- }
- publicStringgetProvince(){
- returnprovince;
- }
- publicvoidsetProvince(Stringprovince){
- this.province=province;
- }
- publicStringgetMode(){
- returnmode;
- }
- publicvoidsetMode(Stringmode){
- this.mode=mode;
- }
- publicStringgetUrl(){
- returnurl;
- }
- publicvoidsetUrl(Stringurl){
- this.url=url;
- }
- publicStringgetSecond_urls(){
- returnsecond_urls;
- }
- publicvoidsetSecond_urls(Stringsecond_urls){
- this.second_urls=second_urls;
- }
- publicString[]getSecond_url(){
- returnsecond_url;
- }
- publicvoidsetSecond_url(String[]second_url){
- this.second_url=second_url;
- StringBufferbuffer=newStringBuffer();
- intcount=second_url.length;
- for(inti=0;i<count;i++){
- buffer.append(second_url[i]);
- if(i!=count-1){
- buffer.append(";");
- }
- }
- second_urls=buffer.toString();
- }
- publicStringgetTypes(){
- returntypes;
- }
- publicvoidsetTypes(Stringtypes){
- this.types=types;
- }
- }
- </span>
我们分析上面的代码同时介绍一下与之相关的配置:
1、是类名,这里我使用的数据表的名字是默认类的小写,当然你还可以指定表名字,使用@DatabaseTable(tableName = "liveitembeans"),
2、主键,在上面的代码中有一行@DatabaseField(id = true)被注解对象就是主键,当然我们有时候使用的一个自增长的id,我们可以设置为@DatabaseField(generatedId = true)来实现,当然还有很多其他的注解配置我这里就不一一说明了,自己可以到官网可以查看找到自己需要的。
二、创建DBHelper
- <spanstyle="font-size:14px;">packagecom.jwzhangjie.capricorntv.db;
- importandroid.content.Context;
- importandroid.database.sqlite.SQLiteDatabase;
- importcom.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
- importcom.j256.ormlite.support.ConnectionSource;
- importcom.j256.ormlite.table.TableUtils;
- importcom.jwzhangjie.capricorntv.bean.LiveItemBean;
- publicclassDBHelperextendsOrmLiteSqliteOpenHelper{
- privatestaticfinalStringDATABASE_NAME="jwzhangjie.db";
- privatestaticfinalintDATABASE_VERSION=1;
- publicDBHelper(Contextcontext){
- super(context,DATABASE_NAME,null,DATABASE_VERSION);
- }
- @Override
- publicvoidonCreate(SQLiteDatabasesqLiteDatabase,
- ConnectionSourceconnectionSource){
- try{
- TableUtils.createTable(connectionSource,LiveItemBean.class);
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- @Override
- publicvoidonUpgrade(SQLiteDatabasesqLiteDatabase,
- ConnectionSourceconnectionSource,intoldVer,intnewVer){
- try{
- TableUtils.dropTable(connectionSource,LiveItemBean.class,true);
- onCreate(sqLiteDatabase,connectionSource);
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- }
- </span>
三、创建操作工具
接下来就是创建一个操作数据库的工具DAO
- <spanstyle="font-size:14px;">packagecom.jwzhangjie.capricorntv.uitls;
- importjava.sql.SQLException;
- importjava.util.ArrayList;
- importjava.util.List;
- importandroid.content.Context;
- importcom.j256.ormlite.dao.Dao;
- importcom.jwzhangjie.capricorntv.bean.LiveItemBean;
- importcom.jwzhangjie.capricorntv.db.DBHelper;
- publicclassDBUtils{
- publicstaticDao<LiveItemBean,Integer>liveDao=null;
- publicDBUtils(Contextcontext){
- if(liveDao==null){
- DBHelperdbHelper=newDBHelper(context);
- try{
- liveDao=dbHelper.getDao(LiveItemBean.class);
- }catch(SQLExceptione){
- e.printStackTrace();
- }
- }
- }
- /**
- *插入直播数据,如果数据存在则进行更新
- *
- *@paramliveItemBean
- */
- publicvoidLiveCreate(LiveItemBeanliveItemBean){
- try{
- liveDao.createOrUpdate(liveItemBean);
- }catch(SQLExceptione){
- e.printStackTrace();
- }
- }
- /**
- *连续进行插入,如果存在则更新
- */
- publicvoidLiveCreates(List<LiveItemBean>lists){
- try{
- for(LiveItemBeanliveItemBean:lists){
- liveDao.createOrUpdate(liveItemBean);
- }
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- /**
- *查询所有的直播元素
- *@return
- */
- publicList<LiveItemBean>getLiveItemBeans(){
- List<LiveItemBean>listsBeans=newArrayList<LiveItemBean>();
- try{
- listsBeans=liveDao.queryForAll();
- }catch(SQLExceptione){
- e.printStackTrace();
- }
- returnlistsBeans;
- }
- }
- </span>
上面实现了创建和查询,在上面的有一个连续插入多个数据,还可以使用OrmLite提供的批处理任务方法如下:
- <spanstyle="font-size:14px;">/**
- *连续进行插入,如果存在则更新
- */
- publicvoidLiveCreates(finalList<LiveItemBean>lists){
- try{
- liveDao.callBatchTasks(newCallable<Void>(){
- @Override
- publicVoidcall()throwsException{
- for(LiveItemBeanliveItemBean:lists){
- liveDao.createOrUpdate(liveItemBean);
- }
- returnnull;
- }
- });
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- </span>
- //findouthowmanyordersaccount-id#10has
- GenericRawResults<String[]>rawResults=
- orderDao.queryRaw(
- "selectcount(*)fromorderswhereaccount_id=10");
- //thereshouldbe1result
- List<String[]>results=rawResults.getResults();
- //theresultsarrayshouldhave1value
- String[]resultArray=results.get(0);
- //thisshouldprintthenumberofordersthathavethisaccount-id
- System.out.println("Account-id10has"+resultArray[0]+"orders");
四、最后释放
当我们应用退出时候,我们需要释放之前对象
- OpenHelperManager.releaseHelper();
- dbHelper=null;
-