Sqlite工具类

本文介绍了一个用于Android应用的SQLite数据库操作类,该类提供了基本的数据库操作功能,如增删改查等,并实现了单例模式确保全局唯一实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. package com.asc.db;  
  2.   
  3. import android.content.ContentValues;  
  4. import android.content.Context;  
  5. import android.database.Cursor;  
  6. import android.database.sqlite.SQLiteDatabase;  
  7. import android.database.sqlite.SQLiteOpenHelper;  
  8.   
  9. /** 
  10.  * 数据库公共类,提供基本数据库操作 
  11.  *  
  12.  * @author raymon 
  13.  *  
  14.  */  
  15. public class DBManager {  
  16.     // 默认数据库  
  17.     private static final String DB_NAME = "asc.db";  
  18.   
  19.     // 数据库版本  
  20.     private static final int DB_VERSION = 1;  
  21.   
  22.     // 执行open()打开数据库时,保存返回的数据库对象  
  23.     private SQLiteDatabase mSQLiteDatabase = null;  
  24.   
  25.     // 由SQLiteOpenHelper继承过来  
  26.     private DatabaseHelper mDatabaseHelper = null;  
  27.   
  28.     // 本地Context对象  
  29.     private Context mContext = null;  
  30.       
  31.     private static DBManager dbConn= null;  
  32.       
  33.     // 查询游标对象  
  34.     private Cursor cursor;  
  35.   
  36.     /** 
  37.      * SQLiteOpenHelper内部类 
  38.      */  
  39.     private static class DatabaseHelper extends SQLiteOpenHelper {  
  40.   
  41.         DatabaseHelper(Context context) {  
  42.             // 当调用getWritableDatabase()或 getReadableDatabase()方法时,创建一个数据库  
  43.             super(context, DB_NAME, null, DB_VERSION);  
  44.         }  
  45.   
  46.         @Override  
  47.         public void onCreate(SQLiteDatabase db) {  
  48.             db.execSQL("CREATE TABLE ad_record(id PRIMARY KEY NOT NULL, adUrl TEXT, apMac TEXT, createDate DATETIME);");  
  49.         }  
  50.   
  51.         @Override  
  52.         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  53.             db.execSQL("DROP TABLE IF EXISTS ad_record");  
  54.             onCreate(db);  
  55.         }  
  56.     }  
  57.   
  58.     /** 
  59.      * 构造函数 
  60.      *  
  61.      * @param mContext 
  62.      */  
  63.     private DBManager(Context mContext) {  
  64.         super();  
  65.         this.mContext = mContext;  
  66.     }  
  67.       
  68.     public static DBManager getInstance(Context mContext){  
  69.         if (null == dbConn) {  
  70.             dbConn = new DBManager(mContext);  
  71.         }  
  72.         return dbConn;  
  73.     }  
  74.   
  75.     /** 
  76.      * 打开数据库 
  77.      */  
  78.     public void open() {  
  79.         mDatabaseHelper = new DatabaseHelper(mContext);  
  80.         mSQLiteDatabase = mDatabaseHelper.getWritableDatabase();  
  81.     }  
  82.   
  83.     /** 
  84.      * 关闭数据库 
  85.      */  
  86.     public void close() {  
  87.         if (null != mDatabaseHelper) {  
  88.             mDatabaseHelper.close();  
  89.         }  
  90.         if (null != cursor) {  
  91.             cursor.close();  
  92.         }  
  93.     }  
  94.   
  95.     /** 
  96.      * 插入数据 
  97.      * @param tableName 表名 
  98.      * @param nullColumn null 
  99.      * @param contentValues 名值对 
  100.      * @return 新插入数据的ID,错误返回-1 
  101.      * @throws Exception 
  102.      */  
  103.     public long insert(String tableName, String nullColumn,  
  104.             ContentValues contentValues) throws Exception {  
  105.         try {  
  106.             return mSQLiteDatabase.insert(tableName, nullColumn, contentValues);  
  107.         } catch (Exception e) {  
  108.             throw e;  
  109.         }  
  110.     }  
  111.   
  112.     /** 
  113.      * 通过主键ID删除数据 
  114.      * @param tableName 表名 
  115.      * @param key 主键名 
  116.      * @param id 主键值 
  117.      * @return 受影响的记录数 
  118.      * @throws Exception 
  119.      */  
  120.     public long delete(String tableName, String key, int id) throws Exception {  
  121.         try {  
  122.             return mSQLiteDatabase.delete(tableName, key + " = " + id, null);  
  123.         } catch (Exception e) {  
  124.             throw e;  
  125.         }  
  126.     }  
  127.       
  128.     /** 
  129.      * 查找表的所有数据 
  130.      * @param tableName 表名 
  131.      * @param columns 如果返回所有列,则填null 
  132.      * @return 
  133.      * @throws Exception 
  134.      */  
  135.     public Cursor findAll(String tableName, String [] columns) throws Exception{  
  136.         try {  
  137.             cursor = mSQLiteDatabase.query(tableName, columns, nullnullnullnullnull);  
  138.             cursor.moveToFirst();  
  139.             return cursor;  
  140.         } catch (Exception e) {  
  141.             throw e;  
  142.         }  
  143.     }  
  144.       
  145.     /** 
  146.      * 根据主键查找数据 
  147.      * @param tableName 表名 
  148.      * @param key 主键名 
  149.      * @param id  主键值 
  150.      * @param columns 如果返回所有列,则填null 
  151.      * @return Cursor游标 
  152.      * @throws Exception  
  153.      */  
  154.     public Cursor findById(String tableName, String key, int id, String [] columns) throws Exception {  
  155.         try {  
  156.             return mSQLiteDatabase.query(tableName, columns, key + " = " + id, nullnullnullnull);  
  157.         } catch (Exception e) {  
  158.             throw e;  
  159.         }  
  160.     }  
  161.       
  162.     /** 
  163.      * 根据条件查询数据 
  164.      * @param tableName 表名 
  165.      * @param names 查询条件 
  166.      * @param values 查询条件值 
  167.      * @param columns 如果返回所有列,则填null 
  168.      * @param orderColumn 排序的列 
  169.      * @param limit 限制返回数 
  170.      * @return Cursor游标 
  171.      * @throws Exception 
  172.      */  
  173.     public Cursor find(String tableName, String [] names, String [] values, String [] columns, String orderColumn, String limit) throws Exception{  
  174.         try {  
  175.             StringBuffer selection = new StringBuffer();  
  176.             for (int i = 0; i < names.length; i++) {  
  177.                 selection.append(names[i]);  
  178.                 selection.append(" = ?");  
  179.                 if (i != names.length - 1) {  
  180.                     selection.append(",");  
  181.                 }  
  182.             }  
  183.             cursor = mSQLiteDatabase.query(true, tableName, columns, selection.toString(), values, nullnull, orderColumn, limit);  
  184.             cursor.moveToFirst();  
  185.             return cursor;  
  186.         } catch (Exception e) {  
  187.             throw e;  
  188.         }  
  189.     }  
  190.       
  191.     /** 
  192.      *  
  193.      * @param tableName 表名 
  194.      * @param names 查询条件 
  195.      * @param values 查询条件值 
  196.      * @param args 更新列-值对 
  197.      * @return true或false 
  198.      * @throws Exception 
  199.      */  
  200.     public boolean udpate(String tableName, String [] names, String [] values, ContentValues args) throws Exception{  
  201.         try {  
  202.             StringBuffer selection = new StringBuffer();  
  203.             for (int i = 0; i < names.length; i++) {  
  204.                 selection.append(names[i]);  
  205.                 selection.append(" = ?");  
  206.                 if (i != names.length - 1) {  
  207.                     selection.append(",");  
  208.                 }  
  209.             }  
  210.             return mSQLiteDatabase.update(tableName, args, selection.toString(), values) > 0;  
  211.         } catch (Exception e) {  
  212.             throw e;  
  213.         }  
  214.     }  
  215.       
  216.     /** 
  217.      * 执行sql语句,包括创建表、删除、插入 
  218.      *  
  219.      * @param sql 
  220.      */  
  221.     public void executeSql(String sql) {  
  222.         mSQLiteDatabase.execSQL(sql);  
  223.     }  
  224.   
  225. } //原文: http://forhope.iteye.com/blog/1461412
<think>好的,我现在需要帮助用户找到关于AndroidSQLite工具类实现或示例代码的信息。首先,用户之前的问题是关于快速排序的,但现在转向了Android开发中的SQLite工具类。这可能是因为他们在开发过程中需要操作数据库,想要一个更高效或结构化的方式来处理SQLite操作。 用户的需求明确提到工具类的实现或示例代码,所以我应该先回顾提供的引用内容。引用[2]提到通过继承SQLiteOpenHelper类来创建数据库,并重写onCreate等方法。引用[3]展示了如何获取数据库实例和执行SQL语句,比如使用execSQL方法。引用[4]提到了aSQLite+库,可以简化SQL拼接。这些信息都是有用的,但用户可能需要更具体的工具类示例,而不仅仅是基础操作。 接下来,我应该考虑如何将这些信息整合成一个工具类。通常,工具类会封装常用的数据库操作,如初始化、增删改查,可能使用单例模式确保只有一个实例。比如,创建DatabaseHelper类继承SQLiteOpenHelper,然后在工具类中管理数据库的打开和关闭,以及提供增删改查的方法。 另外,用户可能希望工具类支持事务处理,或者使用ContentValues来更安全地操作数据,而不是直接写SQL语句。例如,使用insert、update、delete等方法,而不是execSQL。这样可以避免SQL注入的风险,并且代码更易维护。 同时,引用[4]提到的aSQLite+库可能是一个第三方工具,可以简化SQL拼接,但用户可能更倾向于原生的实现方式,所以需要给出两种示例:一种是原生SQLiteOpenHelper封装的工具类,另一种是使用第三方库的示例。 需要注意的是,代码示例需要符合Android的最佳实践,比如在后台线程执行数据库操作,避免主线程阻塞。但工具类本身可能不处理线程问题,而是由调用者负责。不过,可以提及这一点作为注意事项。 最后,用户可能需要相关的扩展问题,比如性能优化、事务处理、数据库升级等,这些都可以作为相关问题列出,帮助他们进一步学习。</think>以下是AndroidSQLite工具类的典型实现方式及示例代码,基于标准开发模式封装: ### 一、基础工具类实现 ```java public class SQLiteHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "my_db"; private static final int DATABASE_VERSION = 1; // 单例模式 private static SQLiteHelper instance; public static synchronized SQLiteHelper getInstance(Context context) { if (instance == null) { instance = new SQLiteHelper(context.getApplicationContext()); } return instance; } private SQLiteHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // 建表语句 String CREATE_TABLE = "CREATE TABLE users (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT," + "name TEXT," + "age INTEGER)"; db.execSQL(CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS users"); onCreate(db); } // 封装插入方法 public long insert(String table, ContentValues values) { SQLiteDatabase db = getWritableDatabase(); return db.insert(table, null, values); } // 封装查询方法 public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String orderBy) { SQLiteDatabase db = getReadableDatabase(); return db.query(table, columns, selection, selectionArgs, null, null, orderBy); } // 封装更新方法 public int update(String table, ContentValues values, String whereClause, String[] whereArgs) { SQLiteDatabase db = getWritableDatabase(); return db.update(table, values, whereClause, whereArgs); } // 封装删除方法 public int delete(String table, String whereClause, String[] whereArgs) { SQLiteDatabase db = getWritableDatabase(); return db.delete(table, whereClause, whereArgs); } } ``` ### 二、使用示例 ```java // 初始化工具类 SQLiteHelper dbHelper = SQLiteHelper.getInstance(context); // 插入数据示例 ContentValues values = new ContentValues(); values.put("name", "张三"); values.put("age", 25); long rowId = dbHelper.insert("users", values); // 查询数据示例 Cursor cursor = dbHelper.query( "users", new String[]{"_id", "name", "age"}, "age > ?", new String[]{"20"}, "age DESC" ); // 事务处理示例 SQLiteDatabase db = dbHelper.getWritableDatabase(); try { db.beginTransaction(); // 执行批量操作 db.setTransactionSuccessful(); } finally { db.endTransaction(); } ``` ### 三、第三方工具库推荐 引用[4]提到的aSQLite+实现方案示例: ```java // 使用链式调用构建查询 SQLite.select() .from(Users.class) .where(Users.NAME.eq("张三")) .and(Users.AGE.gt(20)) .queryList(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值