Android 数据库工具

来源:互联网 发布:汇丰软件开发 待遇 编辑:程序博客网 时间:2024/06/10 03:04
import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;/** * Created by Ice on 2017/4/11. * The abstract class is base utils in you extends this. * You can use it when hand with database. * In createTable() method to create tables * In upGradeDatabase() update your database of tables. */public abstract class BaseDatabase {    private final String TAG = "RRL";    private DbSQLiteOpenHelper helper;    private String databaseName;    private int databaseVersion;    private Context context;    /**     * 基础的数据库构造方法     * This Construction method have default database name     * and default database version . If you want to defined     * database name and database version ,please chose other     * construction.     *     * @param context     */    public BaseDatabase(Context context) {        this.context = context;        databaseName = "AndroidSQLite";        databaseVersion = 1;        helper = new DbSQLiteOpenHelper(context, databaseName, null, databaseVersion);    }    /**     * 自定义数据库名称及路劲和版本的构造方法     * This Construction method you can defined     * database name and database version.     *     * @param context     * @param databaseName    if you want to defined you database path     *                        you should add a path before of database name.     * @param databaseVersion you should upgrade you database when version change     */    public BaseDatabase(Context context, String databaseName, int databaseVersion) {        this.context = context;        helper = new DbSQLiteOpenHelper(context, databaseName, null, databaseVersion);    }    /**     * 创建数据表     * create table     * for example create table if not exists user (_id integer primary key autoincrement,user_name text,user_sex text,user_pwd text)     *     * @param db     */    public abstract void createTable(SQLiteDatabase db);    /**     * 升级数据库     * update grade database     * [newVersion > oldVersion] for example drop table user     *     * @param db         open or write to database object     * @param oldVersion     * @param newVersion     */    public abstract void upGradeDatabase(SQLiteDatabase db, int oldVersion, int newVersion);    /**     * 插入数据     * insert you want what information.     *     * @param table     * @param contentValues     * @return     */    public long insert(String table, ContentValues contentValues) {        long result = -1;        SQLiteDatabase db = helper.getWritableDatabase();        db.beginTransaction();        try {            result = db.insert(table, null, contentValues);            db.setTransactionSuccessful();        } catch (Exception e) {            Log.i(TAG, this.getClass().getSimpleName() + " insert Exception" + e.toString());        }        db.endTransaction();        helper.close();        return result;    }    /**     * 插入数据     * insert you want what information.     *     * @param sql     * @return     */    public void insert(String sql) {        execSQL(sql);    }    /**     * 删除数据     * delete from database what you want to do anything.     *     * @param table     * @param whereClause for example "name = ?"     * @param whereArgs   for example new String[]{"Marry"}     * @return     */    public long delete(String table, String whereClause, String[] whereArgs) {        long result = -1;        SQLiteDatabase db = helper.getWritableDatabase();        db.beginTransaction();        try {            result = db.delete(table, whereClause, whereArgs);            db.setTransactionSuccessful();        } catch (Exception e) {            Log.i(TAG, this.getClass().getSimpleName() + " delete Exception" + e.toString());        }        db.endTransaction();        helper.close();        return result;    }    /**     * 删除数据     * delete from database what you want to do anything.     *     * @param sql     * @return     */    public void delete(String sql) {        execSQL(sql);    }    /**     * 更新数据     * update from your table in database.     *     * @param table     * @param contentValues you is gonging to update values     * @param whereClause   for example "name = ?"     * @param whereArgs     for example new String[]{"Marry"}     * @return     */    public long update(String table, ContentValues contentValues, String whereClause, String[] whereArgs) {        long result = -1;        SQLiteDatabase db = helper.getWritableDatabase();        db.beginTransaction();        try {            result = db.update(table, contentValues, whereClause, whereArgs);            db.setTransactionSuccessful();        } catch (Exception e) {            Log.i(TAG, this.getClass().getSimpleName() + " update Exception" + e.toString());        }        db.endTransaction();        helper.close();        return result;    }    /**     * 更新数据     * update from your table in database.     * for example update user set user_name = 'Jerry' where user_name = 'Marry'     *     * @param sql     * @return     */    public void update(String sql) {        execSQL(sql);    }    /**     * 查询数据     * query from databases and find you what you are gong to finding.     *     * @param sql     * @return     */    public List<Map<String, String>> query(String sql) {        SQLiteDatabase db = helper.getReadableDatabase();        Cursor cursor = db.rawQuery(sql, null);        String[] columnNames = cursor.getColumnNames();        Log.e(TAG, this.getClass().getSimpleName() + " query sql:" + sql + ",column count:" + cursor.getCount() + ",column length:" + columnNames.length);        List<Map<String, String>> queryList = new ArrayList<Map<String, String>>();        while (cursor.moveToNext()) {            Map<String, String> map = new HashMap<>();            for (int i = 0; i < columnNames.length; i++) {                map.put(columnNames[i], cursor.getString(cursor.getColumnIndex(columnNames[i])));            }            queryList.add(map);        }        cursor.close();        helper.close();        return queryList;    }    /**     * 执行SQL语句     * CMD SQL     *     * @param sql     */    public void execSQL(String sql) {        Log.e(TAG, this.getClass().getSimpleName() + " execSQL sql:" + sql);        SQLiteDatabase db = helper.getWritableDatabase();        db.beginTransaction();        try {            db.execSQL(sql);            db.setTransactionSuccessful();//Notice:if you beginTransaction() method and endTransaction() method you must use this method.if you don't while your data insert、update、delete fail.        } catch (Exception e) {            Log.e(TAG, this.getClass().getSimpleName() + " execSQL Exception:" + e.toString());        }        db.endTransaction();        helper.close();    }    /**     * 删除表     * drop table     *     * @param table     */    public void dropTable(String table) {        SQLiteDatabase db = helper.getWritableDatabase();        db.beginTransaction();        String sql = "drop table " + table;        try {            db.execSQL(sql);            Log.e(TAG, this.getClass().getSimpleName() + " dropTable sql:" + sql);            db.setTransactionSuccessful();//Notice:if you beginTransaction() method and endTransaction() method you must use this method.if you don't while your data insert、update、delete fail.        } catch (Exception e) {            Log.e(TAG, this.getClass().getSimpleName() + " execSQL Exception:" + e.toString());        }        db.endTransaction();        helper.close();    }    /**     * 清除表中数据     * truncate table     *     * @param table     */    public void deleteTable(String table) {        SQLiteDatabase db = helper.getWritableDatabase();        db.beginTransaction();        //除去表内的数据,但并不删除表本身        String sql = "delete from " + table;        try {            db.execSQL(sql);            Log.e(TAG, this.getClass().getSimpleName() + " dropTable sql:" + sql);            db.setTransactionSuccessful();//Notice:if you beginTransaction() method and endTransaction() method you must use this method.if you don't while your data insert、update、delete fail.        } catch (Exception e) {            Log.e(TAG, this.getClass().getSimpleName() + " execSQL Exception:" + e.toString());        }        db.endTransaction();        helper.close();    }    /**     * 删除数据库     * delete database     */    public void dropDatabase() {        context.deleteDatabase(helper.getDatabaseName());        Log.e(TAG, this.getClass().getSimpleName() + " dropDatabase databaseName:" + helper.getDatabaseName());    }    /**     * 数据库操作对象类     * The handel with database object class     */    private class DbSQLiteOpenHelper extends SQLiteOpenHelper {        public DbSQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {            super(context, name, factory, version);        }        @Override        public void onCreate(SQLiteDatabase db) {            createTable(db);        }        @Override        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {            upGradeDatabase(db, oldVersion, newVersion);        }    }}


                                             
0 0
原创粉丝点击