Android黑羣出品:SQLite數據庫的使用和升級

SQLite數據庫的基本使用及對返回結果進行簡單的封裝,可直接返回Object或List類型,省去自動轉換成Object或List的麻煩。

主要代碼如下:
Java代碼  收藏代碼
  1. package com.juziku.demo.sqlite;  
  2.    
  3. import java.lang.reflect.Field;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.    
  7.    
  8. import android.content.ContentValues;  
  9. import android.content.Context;  
  10. import android.database.Cursor;  
  11. import android.database.SQLException;  
  12. import android.database.sqlite.SQLiteDatabase;  
  13. import android.util.Log;  
  14.    
  15.    
  16. /** 
  17.  * 基礎DAO,每個DAO都要繼承此類 
  18.  * 
  19.  * @author steven 
  20.  * 
  21.  * http://www.juziku.com/sunlightcs/ 
  22.  * 
  23.  */  
  24. public class BaseDao<T> {  
  25.    
  26.     private Context mContext;  
  27.     private SQLiteDatabase db;  
  28.    
  29.     public Context getmContext() {  
  30.         return mContext;  
  31.     }  
  32.    
  33.     public BaseDao(Context context) {  
  34.         this.mContext = context;  
  35.         DBHelper dbHelper = new DBHelper(mContext, Configuration.DB_NAME,  
  36.                 null, Configuration.DB_VERSION);  
  37.         db = dbHelper.getWritableDatabase();  
  38.     }  
  39.    
  40.     /** 
  41.      * 增加、刪除、修改表時,調用此方法 
  42.      * @param sql  DDL語句 
  43.      * @throws SQLException 
  44.      */  
  45.     public void execute(String sql){  
  46.         db.execSQL(sql);  
  47.     }  
  48.    
  49.     /** 
  50.      * 刪除表中的記錄 
  51.      * @param table   表名 
  52.      * @param whereClause 刪除條件   如:( id>? and time>?) 
  53.      * @param whereArgs   條件裏的參數    用來替換"?"    第1個參數,代表第1個問號;第2個參數,代表第2個問號;依此類推...... 
  54.      * @return  返回刪除的條數 
  55.      */  
  56.     public int delete(String table, String whereClause, String[] whereArgs) {  
  57.         return db.delete(table, whereClause, whereArgs);  
  58.     }  
  59.        
  60.     /** 
  61.      * 插入數據 
  62.      * @param table 表名 
  63.      * @param values    ContentValues對象 
  64.      * @return          返回當前行ID值,如果失敗返回-1 
  65.      */  
  66.     public long insert(String table,    ContentValues values){  
  67.         return this.insert(table, null, values);  
  68.     }  
  69.                
  70.     /** 
  71.      * 插入數據 
  72.      * @param table 表名 
  73.      * @param values    ContentValues對象 
  74.      * @param nullColumnHack   空列 
  75.      * @return          返回當前行ID值,如果失敗返回-1 
  76.      */  
  77.     public long insert(String table, String nullColumnHack,  
  78.             ContentValues values) throws SQLException {  
  79.         return db.insertOrThrow(table, nullColumnHack, values);  
  80.     }  
  81.    
  82.     /** 
  83.      * 修改數據 
  84.      * @param table         表名 
  85.      * @param values        ContentValues對象          表示要修改的列,如: name="steven" 即 values.put("name", "steven"); 
  86.      * @param whereClause   修改條件   如:( id=?) 
  87.      * @param whereArgs     條件裏的參數    用來替換"?"    第1個參數,代表第1個問號;第2個參數,代表第2個問號;依此類推...... 
  88.      * @return              返回修改的條數 
  89.      */  
  90.     public int update(String table, ContentValues values,  
  91.             String whereClause, String[] whereArgs) {  
  92.         return db.update(table, values, whereClause, whereArgs);  
  93.     }  
  94.    
  95.        
  96.    
  97.     /** 
  98.      * 查詢數據 
  99.      * @param table             表名 
  100.      * @param columns           要查詢的列名 
  101.      * @param selection         查詢條件    如:( id=?) 
  102.      * @param selectionArgs     條件裏的參數,用來替換"?" 
  103.      * @return                  返回Cursor 
  104.      */  
  105.     public Cursor query(String table, String[] columns, String selection,  
  106.             String[] selectionArgs) {  
  107.         return db.query(table, columns, selection, selectionArgs, nullnull,  
  108.                 null);  
  109.     }  
  110.        
  111.        
  112.     /** 
  113.      * 查詢數據 
  114.      * @param table             表名 
  115.      * @param columns           要查詢的列名 
  116.      * @param selection         查詢條件    如:( id=?) 
  117.      * @param selectionArgs     條件裏的參數,用來替換"?" 
  118.      * @param orderBy           排序              如:id desc 
  119.      * @return                  返回Cursor 
  120.      */  
  121.     public Cursor query(String table, String[] columns, String selection,  
  122.             String[] selectionArgs, String orderBy) {  
  123.         return db.query(table, columns, selection, selectionArgs, nullnull,  
  124.                 orderBy);  
  125.     }  
  126.        
  127.     /** 
  128.      * 查詢數據 
  129.      * @param distinct          每行是唯一     true:表示唯一       false:表示不唯一 
  130.      * @param table             表名 
  131.      * @param columns           要查詢的列名 
  132.      * @param selection         查詢條件    如:( id=?) 
  133.      * @param selectionArgs     條件裏的參數,用來替換"?" 
  134.      * @param orderBy           排序              如:id desc 
  135.      * @param limit             查詢的條數              如:10 
  136.      * @return                  返回Cursor 
  137.      */  
  138.     public Cursor query(boolean distinct, String table, String[] columns, String selection,  
  139.             String[] selectionArgs, String orderBy, String limit){  
  140.         return db.query(distinct, table, columns, selection, selectionArgs, nullnull, orderBy, limit);  
  141.     }  
  142.        
  143.        
  144.        
  145.        
  146.     /** 
  147.      * 查詢某個字段  
  148.      * @param classz            字節碼      如:String.class 
  149.      * @param table             表名 
  150.      * @param columns           要查詢的列名 
  151.      * @param selection         查詢條件    如:( id=?) 
  152.      * @param selectionArgs     條件裏的參數,用來替換"?" 
  153.      * @return                  返回Object 
  154.      */  
  155.     public Object queryField(Class<?> classz, String table, String[] columns, String selection,  
  156.             String[] selectionArgs){  
  157.         Object o = null;  
  158.         //查詢單條記錄  
  159.         Cursor c = db.query(table, columns, selection, selectionArgs, nullnullnull"1");  
  160.         if(c.moveToFirst()){  
  161.             try {  
  162.                 if(classz == Integer.TYPE) {   //int  
  163.                     o = c.getInt(0);  
  164.                 }else if(classz == String.class){   //String  
  165.                     o = c.getString(0);  
  166.                 }else if(classz == Long.TYPE){   //long  
  167.                     o = c.getLong(0);  
  168.                 }else if(classz == Float.TYPE){   //float  
  169.                     o = c.getFloat(0);  
  170.                 }else if(classz == Double.TYPE){   //double  
  171.                     o = c.getDouble(0);  
  172.                 }else if(classz == Short.TYPE){   //short  
  173.                     o = c.getShort(0);  
  174.                 }  
  175.             } catch (Exception e) {  
  176.                 Log.e("queryField", e.toString());  
  177.             }  
  178.         }  
  179.         c.close();  
  180.         return o;  
  181.     }  
  182.        
  183.        
  184.     /** 
  185.      * 查詢數據    單個對象 
  186.      * @param classz            字節碼      如:String.class 
  187.      * @param table             表名 
  188.      * @param columns           要查詢的列名 
  189.      * @param selection         查詢條件    如:( id=?) 
  190.      * @param selectionArgs     條件裏的參數,用來替換"?" 
  191.      * @return                  返回Object 
  192.      */  
  193.     @SuppressWarnings("unchecked")  
  194.     public T queryObject(Class<?> classz, String table, String[] columns, String selection,  
  195.             String[] selectionArgs){  
  196.            
  197.         //查詢單條記錄  
  198.         Cursor c = db.query(table, columns, selection, selectionArgs, nullnullnull"1");  
  199.         T t = null;  
  200.         if(c.moveToFirst()){  
  201.             try{  
  202.                 //生成新的實例  
  203.                 t = (T) classz.newInstance();  
  204.                    
  205.                 //把列的值,轉換成對象裏屬性的值  
  206.                 columnToField(t, c);  
  207.                    
  208.             }catch(Exception e){  
  209.                 Log.e("newInstance error""生成新實例時出錯 :" + e.toString());  
  210.             }  
  211.         }  
  212.         c.close();  
  213.         return t;  
  214.     }  
  215.        
  216.        
  217.     /** 
  218.      * 查詢數據    帶分頁功能 
  219.      * @param classz            字節碼      如:String.class 
  220.      * @param table             表名 
  221.      * @param columns           要查詢的列名 
  222.      * @param selection         查詢條件    如:( id=?) 
  223.      * @param selectionArgs     條件裏的參數,用來替換"?" 
  224.      * @param orderBy           排序              如:id desc 
  225.      * @param pageNo            頁碼              不分頁時,爲null 
  226.      * @param pageSize          每頁的個數        不分頁時,爲null 
  227.      * @return                  返回List 
  228.      */  
  229.     @SuppressWarnings("unchecked")  
  230.     public List<T> queryList(Class<?> classz, String table, String[] columns, String selection,  
  231.             String[] selectionArgs, String orderBy, Integer pageNo, Integer pageSize){  
  232.            
  233.         //分頁  
  234.         if(!(pageNo == null || pageSize ==null)){  
  235.             //分頁的起始位置  
  236.             int begin = (pageNo -1)*pageSize;  
  237.             orderBy = orderBy + " limit " + begin + ", " + pageSize;  
  238.         }  
  239.            
  240.            
  241.         //查詢數據  
  242.         Cursor c = db.query(table, columns, selection, selectionArgs, nullnull, orderBy);  
  243.            
  244.         List<T> list = new ArrayList<T>();  
  245.         T t = null;  
  246.         while (c.moveToNext()) {  
  247.             try{  
  248.                 //生成新的實例  
  249.                 t = (T) classz.newInstance();  
  250.             }catch(Exception e){  
  251.                 Log.e("newInstance error""生成新實例時出錯 :" + e.toString());  
  252.             }  
  253.                
  254.             //把列的值,轉換成對象裏屬性的值  
  255.             columnToField(t, c);  
  256.                
  257.             list.add(t);  
  258.         }  
  259.         c.close();  
  260.            
  261.         return list;  
  262.     }  
  263.        
  264.        
  265.     /** 
  266.      * 把列的值,轉換成對象裏屬性的值 
  267.      */  
  268.     private void columnToField(T t, Cursor c){  
  269.         //獲取T裏的所有屬性  
  270.         Field[] f = t.getClass().getDeclaredFields();  
  271.         for (int i = 0; i < f.length; i++) {  
  272.                
  273.             int columnIndex = c.getColumnIndex(f[i].getName());  
  274.             //如果爲-1,表示不存在此列  
  275.             if(columnIndex == -1){  
  276.                 continue;  
  277.             }  
  278.                
  279.             Class<?>  classz = f[i].getType();  
  280.             //設置成可訪問,否則不能set值  
  281.             f[i].setAccessible(true);  
  282.                
  283.             try {  
  284.                 if(classz == Integer.TYPE) {   //int  
  285.                     f[i].set(t, c.getInt(columnIndex));  
  286.                 }else if(classz == String.class){   //String  
  287.                     f[i].set(t, c.getString(columnIndex));  
  288.                 }else if(classz == Long.TYPE){   //long  
  289.                     f[i].set(t, c.getLong(columnIndex));  
  290.                 }else if(classz == byte[].class){   //byte  
  291.                     f[i].set(t, c.getBlob(columnIndex));  
  292.                 }else if(classz == Float.TYPE){   //float  
  293.                     f[i].set(t, c.getFloat(columnIndex));  
  294.                 }else if(classz == Double.TYPE){   //double  
  295.                     f[i].set(t, c.getDouble(columnIndex));  
  296.                 }else if(classz == Short.TYPE){   //short  
  297.                     f[i].set(t, c.getShort(columnIndex));  
  298.                 }  
  299.             } catch (Exception e) {  
  300.                 Log.e("column to field error""字段轉換成對象時出錯 :" + e.toString());  
  301.             }  
  302.         }  
  303.     }  
  304.    
  305.    
  306.     /** 
  307.      * 開始事務 
  308.      */  
  309.     protected void beginTransaction() {  
  310.         db.beginTransaction();  
  311.     }  
  312.    
  313.     /** 
  314.      * 提交事務及結束事務 
  315.      */  
  316.     protected void commit() {  
  317.         db.setTransactionSuccessful();  
  318.         db.endTransaction();  
  319.     }  
  320.    
  321.     /** 
  322.      * 回滾事務 
  323.      */  
  324.     protected void rollback() {  
  325.         db.endTransaction();  
  326.     }  
  327.    
  328.     /** 
  329.      * 關閉連接 
  330.      */  
  331.     public void close() {  
  332.         if (db != null && db.isOpen())  
  333.             db.close();  
  334.     }  
  335. }  


數據庫創建、升級
Java代碼  收藏代碼
  1. package com.juziku.demo.sqlite;  
  2.    
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6.    
  7. import android.content.Context;  
  8. import android.database.sqlite.SQLiteDatabase;  
  9. import android.database.sqlite.SQLiteDatabase.CursorFactory;  
  10. import android.database.sqlite.SQLiteOpenHelper;  
  11. import android.util.Log;  
  12.    
  13. public class DBHelper extends SQLiteOpenHelper {  
  14.    
  15.     private Context mContext;  
  16.    
  17.     public DBHelper(Context context, String databaseName,  
  18.             CursorFactory factory, int version) {  
  19.         super(context, databaseName, factory, version);  
  20.         mContext = context;  
  21.     }  
  22.    
  23.     /** 
  24.      * 數據庫第一次創建時調用 
  25.      * */  
  26.     @Override  
  27.     public void onCreate(SQLiteDatabase db) {  
  28.         executeSchema(db, "schema.sql");  
  29.     }  
  30.    
  31.     /** 
  32.      * 數據庫升級時調用 
  33.      * */  
  34.     @Override  
  35.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  36.         //數據庫不升級  
  37.         if (newVersion <= oldVersion) {  
  38.             return;  
  39.         }  
  40.         Configuration.oldVersion = oldVersion;  
  41.    
  42.         int changeCnt = newVersion - oldVersion;  
  43.         for (int i = 0; i < changeCnt; i++) {  
  44.             // 依次執行updatei_i+1文件      由1更新到2 [1-2],2更新到3 [2-3]  
  45.             String schemaName = "update" + (oldVersion + i) + "_"  
  46.                     + (oldVersion + i + 1) + ".sql";  
  47.             executeSchema(db, schemaName);  
  48.         }  
  49.     }  
  50.    
  51.     /** 
  52.      * 讀取數據庫文件(.sql),並執行sql語句 
  53.      * */  
  54.     private void executeSchema(SQLiteDatabase db, String schemaName) {  
  55.         BufferedReader in = null;  
  56.         try {  
  57.             in = new BufferedReader(new InputStreamReader(mContext.getAssets()  
  58.                     .open(Configuration.DB_PATH + "/" + schemaName)));  
  59.             String line;  
  60.             String buffer = "";  
  61.             while ((line = in.readLine()) != null) {  
  62.                 buffer += line;  
  63.                 if (line.trim().endsWith(";")) {  
  64.                     db.execSQL(buffer.replace(";"""));  
  65.                     buffer = "";  
  66.                 }  
  67.             }  
  68.         } catch (IOException e) {  
  69.             Log.e("db-error", e.toString());  
  70.         } finally {  
  71.             try {  
  72.                 if (in != null)  
  73.                     in.close();  
  74.             } catch (IOException e) {  
  75.                 Log.e("db-error", e.toString());  
  76.             }  
  77.         }  
  78.     }  
  79.    
  80. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章