package com.jiuqi.njt.db;
import java.sql.SQLException;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
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 com.jiuqi.njt.model.CModuleBean;
public abstract class DBHelper<T> extends OrmLiteSqliteOpenHelper {
private static final String DBNAME = "csno.db";
private static final int VERSION = 2;
private Dao<T, Integer> dao = null;
public DBHelper(Context context) {
super(context, DBNAME, null, VERSION);
}
@SuppressLint("NewApi")
@Override
public void onCreate(SQLiteDatabase arg0, ConnectionSource arg1) {
try {
TableUtils.createTable(arg1, CModuleBean.class);
} catch (SQLException e) {
e.printStackTrace();
Log.wtf("32", "Unable to create njt.db");
}
}
protected abstract Class<T> getBeanClass();
@SuppressLint("NewApi")
@Override
public void onUpgrade(SQLiteDatabase arg0, ConnectionSource arg1,
int oldVersion, int newVersion) {
if (oldVersion < newVersion) {
try {
TableUtils.dropTable(arg1, CModuleBean.class, true);
TableUtils.createTable(arg1, CModuleBean.class);
} catch (SQLException e) {
e.printStackTrace();
Log.wtf("32", "Unable to upgrade njt.db");
}
}
}
@Override
public void close() {
super.close();
dao = null;
}
protected Dao<T, Integer> getDao() throws SQLException {
if (dao == null) {
dao = super.getDao(getBeanClass());
}
return dao;
}
protected <Bean> Dao<Bean, Integer> getSDao(Class<Bean> c)
throws SQLException {
return super.getDao(c);
}
@SuppressWarnings("hiding")
@Override
public <D extends Dao<T, ?>, T> D getDao(Class<T> clazz)
throws SQLException {
throw new SQLException("不允许使用");
}
/**
* 通过id来创建,对象必须有id字段
*
* @param t
*/
public void create(T t) {
try {
getDao().create(t);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void Upate(T t) {
try {
getDao().update(t);
} catch (SQLException e) {
e.printStackTrace();
}
}
public T findById(int id) {
try {
T t = getDao().queryForId(id);
return t;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
/**
* 通过id来查询
*
* @param t
*/
public int delete(T... ts) {
if (null == ts) {
return 0;
}
try {
for (T t : ts)
getDao().delete(t);
return ts.length;
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
public T find(String recid) throws SQLException {
List<T> list = getDao().queryForEq("recid", recid);
if (null == list || list.isEmpty()) {
return null;
}
return list.get(0);
}
}