主要代碼如下:
- package com.juziku.demo.sqlite;
- import java.lang.reflect.Field;
- import java.util.ArrayList;
- import java.util.List;
- import android.content.ContentValues;
- import android.content.Context;
- import android.database.Cursor;
- import android.database.SQLException;
- import android.database.sqlite.SQLiteDatabase;
- import android.util.Log;
- /**
- * 基礎DAO,每個DAO都要繼承此類
- *
- * @author steven
- *
- * http://www.juziku.com/sunlightcs/
- *
- */
- public class BaseDao<T> {
- private Context mContext;
- private SQLiteDatabase db;
- public Context getmContext() {
- return mContext;
- }
- public BaseDao(Context context) {
- this.mContext = context;
- DBHelper dbHelper = new DBHelper(mContext, Configuration.DB_NAME,
- null, Configuration.DB_VERSION);
- db = dbHelper.getWritableDatabase();
- }
- /**
- * 增加、刪除、修改表時,調用此方法
- * @param sql DDL語句
- * @throws SQLException
- */
- public void execute(String sql){
- db.execSQL(sql);
- }
- /**
- * 刪除表中的記錄
- * @param table 表名
- * @param whereClause 刪除條件 如:( id>? and time>?)
- * @param whereArgs 條件裏的參數 用來替換"?" 第1個參數,代表第1個問號;第2個參數,代表第2個問號;依此類推......
- * @return 返回刪除的條數
- */
- public int delete(String table, String whereClause, String[] whereArgs) {
- return db.delete(table, whereClause, whereArgs);
- }
- /**
- * 插入數據
- * @param table 表名
- * @param values ContentValues對象
- * @return 返回當前行ID值,如果失敗返回-1
- */
- public long insert(String table, ContentValues values){
- return this.insert(table, null, values);
- }
- /**
- * 插入數據
- * @param table 表名
- * @param values ContentValues對象
- * @param nullColumnHack 空列
- * @return 返回當前行ID值,如果失敗返回-1
- */
- public long insert(String table, String nullColumnHack,
- ContentValues values) throws SQLException {
- return db.insertOrThrow(table, nullColumnHack, values);
- }
- /**
- * 修改數據
- * @param table 表名
- * @param values ContentValues對象 表示要修改的列,如: name="steven" 即 values.put("name", "steven");
- * @param whereClause 修改條件 如:( id=?)
- * @param whereArgs 條件裏的參數 用來替換"?" 第1個參數,代表第1個問號;第2個參數,代表第2個問號;依此類推......
- * @return 返回修改的條數
- */
- public int update(String table, ContentValues values,
- String whereClause, String[] whereArgs) {
- return db.update(table, values, whereClause, whereArgs);
- }
- /**
- * 查詢數據
- * @param table 表名
- * @param columns 要查詢的列名
- * @param selection 查詢條件 如:( id=?)
- * @param selectionArgs 條件裏的參數,用來替換"?"
- * @return 返回Cursor
- */
- public Cursor query(String table, String[] columns, String selection,
- String[] selectionArgs) {
- return db.query(table, columns, selection, selectionArgs, null, null,
- null);
- }
- /**
- * 查詢數據
- * @param table 表名
- * @param columns 要查詢的列名
- * @param selection 查詢條件 如:( id=?)
- * @param selectionArgs 條件裏的參數,用來替換"?"
- * @param orderBy 排序 如:id desc
- * @return 返回Cursor
- */
- public Cursor query(String table, String[] columns, String selection,
- String[] selectionArgs, String orderBy) {
- return db.query(table, columns, selection, selectionArgs, null, null,
- orderBy);
- }
- /**
- * 查詢數據
- * @param distinct 每行是唯一 true:表示唯一 false:表示不唯一
- * @param table 表名
- * @param columns 要查詢的列名
- * @param selection 查詢條件 如:( id=?)
- * @param selectionArgs 條件裏的參數,用來替換"?"
- * @param orderBy 排序 如:id desc
- * @param limit 查詢的條數 如:10
- * @return 返回Cursor
- */
- public Cursor query(boolean distinct, String table, String[] columns, String selection,
- String[] selectionArgs, String orderBy, String limit){
- return db.query(distinct, table, columns, selection, selectionArgs, null, null, orderBy, limit);
- }
- /**
- * 查詢某個字段
- * @param classz 字節碼 如:String.class
- * @param table 表名
- * @param columns 要查詢的列名
- * @param selection 查詢條件 如:( id=?)
- * @param selectionArgs 條件裏的參數,用來替換"?"
- * @return 返回Object
- */
- public Object queryField(Class<?> classz, String table, String[] columns, String selection,
- String[] selectionArgs){
- Object o = null;
- //查詢單條記錄
- Cursor c = db.query(table, columns, selection, selectionArgs, null, null, null, "1");
- if(c.moveToFirst()){
- try {
- if(classz == Integer.TYPE) { //int
- o = c.getInt(0);
- }else if(classz == String.class){ //String
- o = c.getString(0);
- }else if(classz == Long.TYPE){ //long
- o = c.getLong(0);
- }else if(classz == Float.TYPE){ //float
- o = c.getFloat(0);
- }else if(classz == Double.TYPE){ //double
- o = c.getDouble(0);
- }else if(classz == Short.TYPE){ //short
- o = c.getShort(0);
- }
- } catch (Exception e) {
- Log.e("queryField", e.toString());
- }
- }
- c.close();
- return o;
- }
- /**
- * 查詢數據 單個對象
- * @param classz 字節碼 如:String.class
- * @param table 表名
- * @param columns 要查詢的列名
- * @param selection 查詢條件 如:( id=?)
- * @param selectionArgs 條件裏的參數,用來替換"?"
- * @return 返回Object
- */
- @SuppressWarnings("unchecked")
- public T queryObject(Class<?> classz, String table, String[] columns, String selection,
- String[] selectionArgs){
- //查詢單條記錄
- Cursor c = db.query(table, columns, selection, selectionArgs, null, null, null, "1");
- T t = null;
- if(c.moveToFirst()){
- try{
- //生成新的實例
- t = (T) classz.newInstance();
- //把列的值,轉換成對象裏屬性的值
- columnToField(t, c);
- }catch(Exception e){
- Log.e("newInstance error", "生成新實例時出錯 :" + e.toString());
- }
- }
- c.close();
- return t;
- }
- /**
- * 查詢數據 帶分頁功能
- * @param classz 字節碼 如:String.class
- * @param table 表名
- * @param columns 要查詢的列名
- * @param selection 查詢條件 如:( id=?)
- * @param selectionArgs 條件裏的參數,用來替換"?"
- * @param orderBy 排序 如:id desc
- * @param pageNo 頁碼 不分頁時,爲null
- * @param pageSize 每頁的個數 不分頁時,爲null
- * @return 返回List
- */
- @SuppressWarnings("unchecked")
- public List<T> queryList(Class<?> classz, String table, String[] columns, String selection,
- String[] selectionArgs, String orderBy, Integer pageNo, Integer pageSize){
- //分頁
- if(!(pageNo == null || pageSize ==null)){
- //分頁的起始位置
- int begin = (pageNo -1)*pageSize;
- orderBy = orderBy + " limit " + begin + ", " + pageSize;
- }
- //查詢數據
- Cursor c = db.query(table, columns, selection, selectionArgs, null, null, orderBy);
- List<T> list = new ArrayList<T>();
- T t = null;
- while (c.moveToNext()) {
- try{
- //生成新的實例
- t = (T) classz.newInstance();
- }catch(Exception e){
- Log.e("newInstance error", "生成新實例時出錯 :" + e.toString());
- }
- //把列的值,轉換成對象裏屬性的值
- columnToField(t, c);
- list.add(t);
- }
- c.close();
- return list;
- }
- /**
- * 把列的值,轉換成對象裏屬性的值
- */
- private void columnToField(T t, Cursor c){
- //獲取T裏的所有屬性
- Field[] f = t.getClass().getDeclaredFields();
- for (int i = 0; i < f.length; i++) {
- int columnIndex = c.getColumnIndex(f[i].getName());
- //如果爲-1,表示不存在此列
- if(columnIndex == -1){
- continue;
- }
- Class<?> classz = f[i].getType();
- //設置成可訪問,否則不能set值
- f[i].setAccessible(true);
- try {
- if(classz == Integer.TYPE) { //int
- f[i].set(t, c.getInt(columnIndex));
- }else if(classz == String.class){ //String
- f[i].set(t, c.getString(columnIndex));
- }else if(classz == Long.TYPE){ //long
- f[i].set(t, c.getLong(columnIndex));
- }else if(classz == byte[].class){ //byte
- f[i].set(t, c.getBlob(columnIndex));
- }else if(classz == Float.TYPE){ //float
- f[i].set(t, c.getFloat(columnIndex));
- }else if(classz == Double.TYPE){ //double
- f[i].set(t, c.getDouble(columnIndex));
- }else if(classz == Short.TYPE){ //short
- f[i].set(t, c.getShort(columnIndex));
- }
- } catch (Exception e) {
- Log.e("column to field error", "字段轉換成對象時出錯 :" + e.toString());
- }
- }
- }
- /**
- * 開始事務
- */
- protected void beginTransaction() {
- db.beginTransaction();
- }
- /**
- * 提交事務及結束事務
- */
- protected void commit() {
- db.setTransactionSuccessful();
- db.endTransaction();
- }
- /**
- * 回滾事務
- */
- protected void rollback() {
- db.endTransaction();
- }
- /**
- * 關閉連接
- */
- public void close() {
- if (db != null && db.isOpen())
- db.close();
- }
- }
數據庫創建、升級
- package com.juziku.demo.sqlite;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteDatabase.CursorFactory;
- import android.database.sqlite.SQLiteOpenHelper;
- import android.util.Log;
- public class DBHelper extends SQLiteOpenHelper {
- private Context mContext;
- public DBHelper(Context context, String databaseName,
- CursorFactory factory, int version) {
- super(context, databaseName, factory, version);
- mContext = context;
- }
- /**
- * 數據庫第一次創建時調用
- * */
- @Override
- public void onCreate(SQLiteDatabase db) {
- executeSchema(db, "schema.sql");
- }
- /**
- * 數據庫升級時調用
- * */
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- //數據庫不升級
- if (newVersion <= oldVersion) {
- return;
- }
- Configuration.oldVersion = oldVersion;
- int changeCnt = newVersion - oldVersion;
- for (int i = 0; i < changeCnt; i++) {
- // 依次執行updatei_i+1文件 由1更新到2 [1-2],2更新到3 [2-3]
- String schemaName = "update" + (oldVersion + i) + "_"
- + (oldVersion + i + 1) + ".sql";
- executeSchema(db, schemaName);
- }
- }
- /**
- * 讀取數據庫文件(.sql),並執行sql語句
- * */
- private void executeSchema(SQLiteDatabase db, String schemaName) {
- BufferedReader in = null;
- try {
- in = new BufferedReader(new InputStreamReader(mContext.getAssets()
- .open(Configuration.DB_PATH + "/" + schemaName)));
- String line;
- String buffer = "";
- while ((line = in.readLine()) != null) {
- buffer += line;
- if (line.trim().endsWith(";")) {
- db.execSQL(buffer.replace(";", ""));
- buffer = "";
- }
- }
- } catch (IOException e) {
- Log.e("db-error", e.toString());
- } finally {
- try {
- if (in != null)
- in.close();
- } catch (IOException e) {
- Log.e("db-error", e.toString());
- }
- }
- }
- }