zoukankan      html  css  js  c++  java
  • 经常用得到的安卓数据库基类

    Java代码  收藏代码
    1. //创建数据库  
    2. public class DBCreate {  
    3.     public static void CreateDatabase(SQLiteDatabase db) {  
    4.         db.beginTransaction();  
    5.         try {  
    6.             create_NetTaskBuffer(db);  
    7.   
    8.             insert_SQL(db);  
    9.   
    10.             db.setTransactionSuccessful();  
    11.         } catch (Exception e) {  
    12.             e.printStackTrace();  
    13.         } finally {  
    14.             db.endTransaction();  
    15.         }  
    16.     }  
    17.   
    18.     // 缓存  
    19.     private static void create_NetTaskBuffer(SQLiteDatabase db) {  
    20.         db.execSQL("DROP TABLE IF EXISTS NetTaskBuffer");  
    21.         StringBuilder sql = new StringBuilder();  
    22.         sql.append("CREATE TABLE IF NOT EXISTS NetTaskBuffer (");  
    23.         sql.append(" id INTEGER PRIMARY KEY AUTOINCREMENT,"); // 这一列不能修改  
    24.         sql.append(" label TEXT COLLATE NOCASE,"); //  
    25.         sql.append(" param TEXT COLLATE NOCASE,"); //  
    26.         sql.append(" result TEXT COLLATE NOCASE,"); //  
    27.         sql.append(" remark TEXT COLLATE NOCASE,");  
    28.         sql.append(" time LONG)"); //  
    29.         db.execSQL(sql.toString());  
    30.     }  
    31.   
    32.     // 插入语句,初始化数据库使用  
    33.     private static void insert_SQL(SQLiteDatabase db) {  
    34.           
    35.     }  
    36. }  
    37.   
    38.   
    39.   
    40. //----------------------数据库操作基类--------------------------------------//  
    41.   
    42.   
    43. /** 
    44.  * 数据库基本操作类,数据库的创建,更新的操作都在这里进行 
    45.  *  
    46.  * @author yizhe 
    47.  * @date 2014-9-11 
    48.  */  
    49. public abstract class DBHelper extends SQLiteOpenHelper {  
    50.   
    51.     static String name = "hk.db"; // 数据库名称  
    52.     static CursorFactory cursorFactory = null;  
    53.     static int version = 1000;// 初始版本:1000  
    54.     Context context;  
    55.   
    56.     protected ContentValues contentValues; // cursor对象转行中介,给子类使用  
    57.   
    58.     protected String tableName;  
    59.   
    60.     protected DBHelper(Context context, String tableName) {  
    61.         super(context, name, cursorFactory, version);  
    62.         this.context = context;  
    63.         this.tableName = tableName;  
    64.     }  
    65.   
    66.     /** 
    67.      * 软件第一次安装的时候会调用,覆盖安装不会调用 
    68.      */  
    69.     public void onCreate(SQLiteDatabase db) {  
    70.         // 所有表的创建过程都在这里进行  
    71.         DBCreate.createDatabase(db);  
    72.     }  
    73.   
    74.     /** 
    75.      * 覆盖安装,当版本号version发生变化的时候,这个方法才会被调用,而且只执行一次 
    76.      */  
    77.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
    78.         onCreate(db);  
    79.         // if (oldVersion < 109) {  
    80.         // onCreate(db);  
    81.         // } else {  
    82.         // }  
    83.     }  
    84.   
    85.     /** 
    86.      * 每次成功打开数据库后首先被执行 
    87.      */  
    88.     public void onOpen(SQLiteDatabase db) {  
    89.         super.onOpen(db); // 每次成功打开数据库后首先被执行  
    90.     }  
    91.   
    92.     public void finalize() {  
    93.         close();  
    94.     }  
    95.   
    96.     // --------------------------sql方法---------------------------------//  
    97.     /** 
    98.      * 执行sql,没有返回 
    99.      */  
    100.     public void execSQL(String sql) {  
    101.         System.out.println("==execSQL==" + sql);  
    102.         SQLiteDatabase db = getWritableDatabase();  
    103.         db.execSQL(sql);  
    104.         db.close();  
    105.     }  
    106.   
    107.     /** 
    108.      * 批量执行sql,内部启用事务 
    109.      *  
    110.      * @param list 
    111.      *            sql列表 
    112.      * @return 是否执行成功 
    113.      */  
    114.     public boolean execSQLBatch(ArrayList<String> list) {  
    115.         SQLiteDatabase db = getWritableDatabase();  
    116.         db.beginTransaction();  
    117.         try {  
    118.             for (String sql : list) {  
    119.                 db.execSQL(sql);  
    120.             }  
    121.             db.setTransactionSuccessful();  
    122.         } catch (Exception e) {  
    123.             e.printStackTrace();  
    124.             return false;  
    125.         } finally {  
    126.             db.endTransaction();  
    127.             db.close();  
    128.         }  
    129.         return true;  
    130.     }  
    131.   
    132.     /** 
    133.      * 根据id删除记录 
    134.      *  
    135.      * @param id 
    136.      *            表中必须有"id"字段 
    137.      * @return the number of rows affected if a whereClause is passed in, 0 
    138.      *         otherwise. To remove all rows and get a count pass "1" as the 
    139.      *         whereClause. 
    140.      */  
    141.     public int delete(int id) {  
    142.         SQLiteDatabase db = getWritableDatabase();  
    143.         int result = db.delete(tableName, "id=?", new String[] { id + "" });  
    144.         db.close();  
    145.         return result;  
    146.     }  
    147.   
    148.     /** 
    149.      * 删除: 只需要写where 条件(不带where) 和 参数 
    150.      *  
    151.      * @param whereStr 
    152.      *            例如: "id=?" 
    153.      * @param arr 
    154.      *            例如: new String[] { "123" } 
    155.      * @return 受影响的行 
    156.      */  
    157.     public int delete(String whereStr, String[] arr) {  
    158.         SQLiteDatabase db = getWritableDatabase();  
    159.         int result = db.delete(tableName, whereStr, arr);  
    160.         db.close();  
    161.         return result;  
    162.     }  
    163.   
    164.     /** 
    165.      * 清空表 
    166.      */  
    167.     public void clearTable() {  
    168.         SQLiteDatabase db = getWritableDatabase();  
    169.         db.execSQL("delete from " + tableName);  
    170.         db.close();  
    171.     }  
    172.   
    173.     /** 
    174.      * 通用查询,多用于事务中 
    175.      */  
    176.     public static Cursor Query(SQLiteDatabase db, String sql) {  
    177.         System.out.println("==Query==" + sql);  
    178.         return db.rawQuery(sql, new String[] {});  
    179.     }  
    180.   
    181.     /** 
    182.      * 通用执行sql,,多用于事务中 
    183.      *  
    184.      */  
    185.     public static void execSQL(SQLiteDatabase db, String sql) {  
    186.         System.out.println("==execSQL==" + sql);  
    187.         db.execSQL(sql);  
    188.     }  
    189.   
    190. }  
    191.   
    192. //-------------------------下面是一个具体实现的DEMO-------------------------------//  
    193. /** 
    194.  * dao类,实现基本的数据库操作<br/> 
    195.  * 需要保存到数据库中的对象的属性不能使用基本类型,建议只使用Integer 和 String<br/> 
    196.  * 做为通用对象,从demo创建只要修改tableName即可 
    197.  *  
    198.  * @author yizhe 
    199.  * @date 2012-5-18 
    200.  */  
    201. public class NetTaskBufferDao extends DBHelper {  
    202.     int expiryDays = 10; // 数据缓存有效期  
    203.   
    204.     public NetTaskBufferDao(Context context) {  
    205.         super(context, "NetTaskBuffer");  
    206.     }  
    207.   
    208.     // pojo的整数都需要使用Long类型 或者Integer类型 建议使用Long  
    209.     public void iniContentValues(NetTaskBuffer pojo) {  
    210.         contentValues = new ContentValues();  
    211.         contentValues.put("id", pojo.id);  
    212.         contentValues.put("label", pojo.label);  
    213.         contentValues.put("param", pojo.param);  
    214.         contentValues.put("result", pojo.result);  
    215.         contentValues.put("remark", pojo.remark);  
    216.         contentValues.put("time", pojo.time);  
    217.     }  
    218.   
    219.     public NetTaskBuffer setBaseItem(Cursor cursor) {  
    220.         NetTaskBuffer pojo = new NetTaskBuffer();  
    221.         pojo.id = cursor.getInt(cursor.getColumnIndex("id"));  
    222.         pojo.label = cursor.getString(cursor.getColumnIndex("label"));  
    223.         pojo.param = cursor.getString(cursor.getColumnIndex("param"));  
    224.         pojo.result = cursor.getString(cursor.getColumnIndex("result"));  
    225.         pojo.remark = cursor.getString(cursor.getColumnIndex("remark"));  
    226.         pojo.time = cursor.getLong(cursor.getColumnIndex("time"));  
    227.         return pojo;  
    228.     }  
    229.   
    230.     // --------------------自定义方法--------------------------------//  
    231.     public String getBuffer(String label, String param) {  
    232.         String sql = "select * from " + tableName  
    233.                 + " where label=? and param=? ";  
    234.         NetTaskBuffer obj = getOneAsSQL(sql, new String[] { label, param });  
    235.         if (null == obj) {  
    236.             return null;  
    237.         }  
    238.         Date time = new Date(obj.time);  
    239.         Calendar c = Calendar.getInstance();  
    240.   
    241.         c.add(Calendar.DAY_OF_MONTH, -expiryDays);  
    242.         if (time.compareTo(c.getTime()) < 0) {  
    243.             delete(obj.id);  
    244.             return null;  
    245.         }  
    246.         return obj.result;  
    247.     }  
    248.   
    249.     public String getBuffer(String label, String param, String remark) {  
    250.         String sql = "select * from " + tableName  
    251.                 + " where label=? and param=? and remark=?";  
    252.         NetTaskBuffer obj = getOneAsSQL(sql, new String[] { label, param,  
    253.                 remark });  
    254.         if (null == obj) {  
    255.             return null;  
    256.         }  
    257.         Date time = new Date(obj.time);  
    258.         Calendar c = Calendar.getInstance();  
    259.   
    260.         c.add(Calendar.DAY_OF_MONTH, -expiryDays);  
    261.         if (time.compareTo(c.getTime()) < 0) {  
    262.             delete(obj.id);  
    263.             return null;  
    264.         }  
    265.         return obj.result;  
    266.     }  
    267.   
    268.     public void deleteBuffer(String label) {  
    269.         String whereSql = " label=?";  
    270.         delete(whereSql, new String[] { label });  
    271.     }  
    272.   
    273.     public void deleteBuffer(String label, String param) {  
    274.         String whereSql = " label=? and param=?";  
    275.         delete(whereSql, new String[] { label, param });  
    276.     }  
    277.   
    278.     public void deleteBuffer(String label, String param, String remark) {  
    279.         String whereSql = " label=? and param=? and remark=?";  
    280.         delete(whereSql, new String[] { label, param, remark });  
    281.     }  
    282.   
    283.     // --------------------基础方法---------------------------------//  
    284.   
    285.     /** 
    286.      * 根据sql获取list 
    287.      */  
    288.     public ArrayList<NetTaskBuffer> getListAsSQL(String sql) {  
    289.         SQLiteDatabase db = getReadableDatabase();  
    290.         Cursor cursor = db.rawQuery(sql, new String[] {});  
    291.         ArrayList<NetTaskBuffer> itemList = new ArrayList<NetTaskBuffer>();  
    292.         for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {  
    293.             itemList.add(setBaseItem(cursor));  
    294.         }  
    295.         cursor.close();  
    296.         db.close();  
    297.         return itemList;  
    298.     }  
    299.   
    300.     /** 
    301.      * 根据ID获取一条记录 
    302.      */  
    303.     public NetTaskBuffer getById(int id) {  
    304.         String sql = "select * from " + tableName + " where id=" + id;  
    305.         return getOneAsSQL(sql, null);  
    306.     }  
    307.   
    308.     /** 
    309.      * 返回结果中的提一条记录 
    310.      */  
    311.     public NetTaskBuffer getOneAsSQL(String sql, String[] arr) {  
    312.         SQLiteDatabase db = getReadableDatabase();  
    313.         Cursor cursor = db.rawQuery(sql, arr);  
    314.         try {  
    315.             if (null != cursor && cursor.getCount() > 0) {  
    316.                 cursor.moveToFirst();  
    317.                 return setBaseItem(cursor);  
    318.             }  
    319.         } finally {  
    320.             cursor.close();  
    321.             db.close();  
    322.         }  
    323.         return null;  
    324.     }  
    325.   
    326.     /** 
    327.      * 保存对象到数据库,自动判断插入还是更像 
    328.      *  
    329.      * @return 返回更新的记录数,或者 插入数据的id,如果返回值<=0表示失败 
    330.      */  
    331.     public long save(NetTaskBuffer pojo) {  
    332.         if (null == pojo.time || 0 == pojo.time) {  
    333.             pojo.time = new Date().getTime();  
    334.         }  
    335.         Long idOrEffectRows = 0l;  
    336.         if (null == pojo.id || pojo.id < 1) {  
    337.             idOrEffectRows = insert(pojo);  
    338.         } else {  
    339.             idOrEffectRows = (long) update(pojo);  
    340.         }  
    341.         return idOrEffectRows;  
    342.     }  
    343.   
    344.     /** 
    345.      * 添加数据,自动插入id 
    346.      *  
    347.      * @return the row ID of the newly inserted row, or -1 if an error occurred 
    348.      */  
    349.     public long insert(NetTaskBuffer pojo) {  
    350.         SQLiteDatabase db = getWritableDatabase();// 获取可写SQLiteDatabase对象  
    351.         iniContentValues(pojo); // ContentValues类似map,存入的是键值对  
    352.         long result = db.insert(tableName, null, contentValues);  
    353.         if (result != -1) {  
    354.             pojo.id = (int) result;  
    355.         }  
    356.         db.close();  
    357.         return result;  
    358.     }  
    359.   
    360.     /** 
    361.      * 根据ID更新记录的,跟插入的很像 
    362.      *  
    363.      * @return the number of rows affected 
    364.      *  
    365.      */  
    366.     public int update(NetTaskBuffer pojo) {  
    367.         SQLiteDatabase db = getWritableDatabase();  
    368.         iniContentValues(pojo); // 初始化键值对  
    369.         int result = db.update(tableName, contentValues, "id=?",  
    370.                 new String[] { pojo.id + "" });  
    371.         db.close();  
    372.         return result;  
    373.     }  
    374.   
    375. }  

    安卓标准数据库构建.zip (9.2 KB)

  • 相关阅读:
    [NOIP2015] 子串 题解
    [NOIP2011] 聪明的质检员 题解
    二进制的一些概念
    [NOIP2012] 借教室 题解
    [POJ3764] The XOR Longest Path 题解
    关于本博客
    【SC-MY限定】让填写问卷星成为自动化!
    JZOJ5833 永恒
    九校联考-DL24凉心模拟Day2总结
    【简解】SP7556 Stock Charts
  • 原文地址:https://www.cnblogs.com/xiaochao1234/p/4030495.html
Copyright © 2011-2022 走看看