Android 数据库工具

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 Relin 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 int DATABASE_VERSION = 1;
    private final String DATABASE_NAME = "AndroidSQLite";
    private Context context;
    private int databaseVersion;
    private String databaseName;
    private DbSQLiteOpenHelper helper;
    protected final String CREATE_TABLE_HEAD = "create table if not exists ";
    protected final String CREATE_PRIMARY_KEY = "_id integer primary key autoincrement,";

    /**
     * 基础的数据库构造方法
     * 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 = DATABASE_NAME;
        databaseVersion = DATABASE_VERSION;
        if (helper == null) {
            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;
        if (helper == null) {
            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)
     * then db.execSQL(TABLE_USER_SQL)
     *
     * @param db
     */
    public void onCreate(SQLiteDatabase db) {
    }

    /**
     * 建表
     * Create the SQL statement for the table.
     *
     * @param table   表名
     * @param columns 列
     * @return
     */
    public void createTable(SQLiteDatabase db,String table,String [] columns) {
        if (columns == null) {
            return;
        }
        StringBuffer sb = new StringBuffer();
        sb.append(CREATE_TABLE_HEAD + table);
        sb.append(" (");
        sb.append(CREATE_PRIMARY_KEY);
        for (String key : columns) {
            sb.append(key + " text");
            sb.append(",");
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append(")");
        Log.e(this.getClass().getSimpleName(), "createTable:" + sb.toString());
        db.execSQL(sb.toString());
    }

    /**
     * 升级数据库
     * 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 onUpgrade(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(this.getClass().getSimpleName(), 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(this.getClass().getSimpleName(), 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(this.getClass().getSimpleName(), 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(this.getClass().getSimpleName(), 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(this.getClass().getSimpleName(), 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(this.getClass().getSimpleName(), 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(this.getClass().getSimpleName(), 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(this.getClass().getSimpleName(), 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(this.getClass().getSimpleName(), 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(this.getClass().getSimpleName(), this.getClass().getSimpleName() + " execSQL Exception:" + e.toString());
        }
        db.endTransaction();
        helper.close();
    }

    /**
     * 删除数据库
     * delete database
     */
    public void dropDatabase() {
        context.deleteDatabase(helper.getDatabaseName());
        Log.e(this.getClass().getSimpleName(), 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) {
            BaseDatabase.this.onCreate(db);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            BaseDatabase.this.onUpgrade(db, oldVersion, newVersion);
        }
    }

}

猜你喜欢

转载自blog.csdn.net/u012127961/article/details/52765180
今日推荐