ORMlite通过Java注解的方式来建立起与数据库的映射关系,在Android面向数据库开发中,是一个比较流行的开源框架,方便操作而且功能强大
ORMLite的优缺点
优点:轻量级、使用简单、封装完善、文档全面
缺点:基于反射,效率较低,缺少中文翻译文档
添加到项目:
添加库文件到项目libs下,添加为库
ormlite-android-5.0.jar、ormlite-android-5.0-sources.jar
ormlite-core-5.0、ormlite-core-5.0-sources.jar
继承OrmLiteSqliteOpenHelper类定义数据库帮助类
可以在程序被安装时创建或者升级数据库
onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource)
onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion)
下面就是帮助类,可直接粘贴复制:
package com.jerehedu.jereduch10.ormlistdemo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String TABLE_NAME = "ormtest.db";
private Map<String, Dao> daos = new HashMap<String, Dao>();
private static DatabaseHelper instance;
private DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase database,
ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, User1.class);
// TableUtils.createTable(connectionSource, News.class);
//如果有多个表,都在这里创建
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase database,
ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
TableUtils.dropTable(connectionSource, User1.class, true);
onCreate(database, connectionSource);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 单例获取该Helper
*
* @param context
* @return
*/
public static synchronized DatabaseHelper getHelper(Context context) {
context = context.getApplicationContext();
if (instance == null) {
synchronized (DatabaseHelper.class) {
if (instance == null) {
instance = new DatabaseHelper(context);
}
}
}
return instance;
}
public synchronized Dao getDao(Class clazz) throws SQLException {
Dao dao = null;
String className = clazz.getSimpleName();
if (daos.containsKey(cla