package com.jiuqi.njt.register.city; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import android.annotation.SuppressLint; 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; /** * 数据操作基本工具类 * @author joe * */ @SuppressWarnings("unchecked") public abstract class BaseDBHelper<T> extends OrmLiteSqliteOpenHelper { private static final String DBNAME ="NJT.db" ; private static final int VERSION = 2; private Dao<T, Integer> dao = null; public BaseDBHelper(Context context) { super(context, DBNAME, null, VERSION); } @SuppressLint("NewApi") @Override public void onCreate(SQLiteDatabase arg0, ConnectionSource arg1) { try { for (Class itemClass : DatabaseConfigUtil.getMainDbEntityClasses()) { TableUtils.createTable(arg1, itemClass); } } catch (SQLException e) { e.printStackTrace(); } } protected abstract Class<T> getBeanClass(); @SuppressLint("NewApi") @Override public void onUpgrade(SQLiteDatabase arg0, ConnectionSource arg1, int oldVersion, int newVersion) { if (oldVersion < newVersion) { try { for (Class itemClass : DatabaseConfigUtil.getMainDbEntityClasses()) { TableUtils.dropTable(arg1, itemClass,true); } for (Class itemClass : DatabaseConfigUtil.getMainDbEntityClasses()) { TableUtils.createTable(arg1, itemClass); } } catch (SQLException e) { e.printStackTrace(); } } } @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; } } public List<T> queryAll(){ List<T> data=new ArrayList<T>(); try { data = getDao().queryForAll(); } catch (SQLException e) { e.printStackTrace(); } return data; } /** * 通过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); } }