Android Sqlite3学习

一.Sqlite介绍

SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。它是D.RichardHipp建立的公有领域项目。它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,Android使用它保存本地数据

安装Sqlite3

sudo apt-get install sqlite3

Sqlie 支持的基本数据类型
类型 介绍
NULL 值是一个 NULL 值。
INTEGER 值是一个带符号的整数,根据值的大小存储在 1、2、3、4、6 或 8 字节中。
REAL 值是一个浮点值,存储为 8 字节的 IEEE 浮点数字。
TEXT 值是一个文本字符串,使用数据库编码(UTF-8、UTF-16BE 或 UTF-16LE)存储。
BLOB 值是一个 blob 数据,完全根据它的输入存储。
Sqlite3的sql语句

以创建表book(bookname,version),book2(bookname,version,author)为例

创建数据库
sqlite3 tes.db

创建表
create table book(bookname TEXT,version INTEGER);
create table book2(bookname TEXT,version INTEGER,author TEXT);

显示表
.table

删除表则命令为
drop table book;

插入数据
insert into book (bookname, version) values (‘name1’, 1);
insert into book values(‘name2’,2);

删除数据
delete from book where version = 2;

数据更新命令
update book set bookname='name22’where version = 2;

查询数据
select * from book;

显示各表结构
select * from sqlite_master where type=“table” ;

迁移表
book2比多1列.所以加空格’ ’
insert into book2 select *,’ ’ from book;
insert into book select bookname,version from book2;

二.Android Sqlite数据库

完成存储app信息的数据库
创建数据库

public class AppDataBase extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "AppInfo.db";
    private static final String TAG = "AppDataBase";
    private static final String TB_NAME = "appinfo";
    private static final int DATABASE_VERSION = 1;
    private static final String SQL = "create table " + TB_NAME + " ( " +
            "isSystem INTEGER," +
            "appname TEXT," +
            "packageName TEXT," +
            "versionName TEXT," +
            "versionCode INTEGER," +
            "launcherlist TEXT," +
            "appIcon BLOB," +
            "appDir TEXT" +
            ")";

    public AppDataBase(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL);
        MyLog.i(SQL + " start");
    }
}

保存,更新,加载,删除APP信息

   public boolean deleteAppinfo(String packagename) {
        int count = sqLiteDatabase.delete(TB_NAME, "packageName=?",
                new String[]{packagename});
        return count != 0;
    }

    public List<AppInfo> loadAppinfos(boolean isASystem) {
        List<AppInfo> appInfos = new ArrayList<>();
        String isSystem = isASystem ? "0" : "1";
        Cursor cursor = sqLiteDatabase.query(TB_NAME,
                null, "isSystem=?",
                new String[]{isSystem}, null,
                null, null);
        if (cursor != null) {
            AppInfo appInfo;
            while (cursor.moveToNext()) {
                String appname = cursor.getString(cursor.getColumnIndex("appname"));
                String packageName = cursor.getString(cursor.getColumnIndex("packageName"));
                String versionName = cursor.getString(cursor.getColumnIndex("versionName"));
                String appDir = cursor.getString(cursor.getColumnIndex("appDir"));
                List<String> launcherlist = stringTolist(cursor.getString(cursor.getColumnIndex("launcherlist")));
                int versionCode = cursor.getInt(cursor.getColumnIndex("versionCode"));
                Drawable appIcon = byteToDrawable(cursor.getBlob(cursor.getColumnIndex("appIcon")));

                appInfo = new AppInfo();
                appInfo.setAppName(appname);
                appInfo.setPackageName(packageName);
                appInfo.setAppDir(appDir);
                appInfo.setVersionName(versionName);
                appInfo.setVersionCode(versionCode);
                appInfo.setAppIcon(appIcon);
                appInfo.addLauncher(launcherlist);
                appInfos.add(appInfo);

            }
        }

        return appInfos;
    }

    public boolean saveAppinfo(AppInfo appInfo, boolean isASystem) {
        int isSystem = isASystem ? 0 : 1;
        String appname = (String) appInfo.getAppName();
        String packageName = (String) appInfo.getPackageName();
        String versionName = (String) appInfo.getVersionName();
        String launcherlist = covertLuncher(appInfo.getLauncherlist());
        String appDir = (String) appInfo.getAppDir();
        int versionCode = appInfo.getVersionCode();
        byte[] appIcon = drawableToByte(appInfo.getAppIcon());

        ContentValues cv = new ContentValues();
        cv.put("isSystem", isSystem);
        cv.put("appname", appname);
        cv.put("packageName", packageName);
        cv.put("versionName", versionName);
        cv.put("versionCode", versionCode);
        cv.put("launcherlist", launcherlist);
        cv.put("appDir", appDir);
        cv.put("appIcon", appIcon);


        Cursor cursor = sqLiteDatabase.query(TB_NAME,
                null, "packageName=?",
                new String[]{packageName}, null,
                null, null);

        long result = 0;
        if (cursor != null && cursor.moveToNext()) {
            cursor.close();

            MyLog.i("update " + packageName);
            sqLiteDatabase.update(TB_NAME, cv, "packageName=?", new String[]{"+packageName+"});
        } else {
            MyLog.i("insert " + packageName);
            result = sqLiteDatabase.insert(TB_NAME, null, cv);
        }


        return result != 0;
    }

因为Sqlite3不支持List和Bitmap,需要把list转String,Bitmap转为二进制

    private List<String> stringTolist(String str) {
        if (str == null || str.length() == 0) {
            return new ArrayList<>();
        }
        String[] listEntry = str.split(",");
        List<String> resultList = new ArrayList<>(Arrays.asList(listEntry));
        return resultList;
    }

    private String covertLuncher(List<String> list) {
        if (list == null || list.size() == 0) {
            return STRING_EMPTY;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            stringBuilder.append(list.get(i));
            if (i < list.size() - 1) {
                stringBuilder.append(",");
            }
        }

        return stringBuilder.toString();
    }
    private synchronized byte[] drawableToByte(Drawable drawable) {
        if (drawable == null) {
            return null;
        }
        Bitmap bitmap = Bitmap
                .createBitmap(
                        drawable.getIntrinsicWidth(),
                        drawable.getIntrinsicHeight(),
                        drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        int size = bitmap.getWidth() * bitmap.getHeight() * 4;
        ByteArrayOutputStream baos = new ByteArrayOutputStream(size);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] imagedata = baos.toByteArray();
        return imagedata;
    }


    private synchronized Drawable byteToDrawable(byte[] img) {
        Bitmap bitmap;
        if (img != null) {
            bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);
            Drawable drawable = new BitmapDrawable(bitmap);
            return drawable;
        }
        return null;
    }

升级表,增加userid字段

    private static final String SQL_VERSION2 = "create table if not exists " + TB_NAME + " ( " +
            "isSystem INTEGER," +
            "appname TEXT," +
            "userid TEXT," +
            "packageName TEXT," +
            "versionName TEXT," +
            "versionCode INTEGER," +
            "launcherlist TEXT," +
            "appIcon BLOB," +
            "appDir TEXT" +
            ")";
         
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion == 1 && newVersion == 2) {

            // step 1:获取原表所有信息
            Cursor cursor = db.rawQuery("select * from " + TB_NAME, null);

            // step 2:更改原表未临时表
            String tempTableName = "_temp_" + TB_NAME;
            db.execSQL("alter table " + TB_NAME + " rename to " + tempTableName);

            // step 3:创建新表
            db.execSQL(SQL_VERSION2);
            if (cursor == null) {
                // 如果游标为空,说明旧表中没有数据,如果是这种情况那就可以直接改表的字段,不需要转移数据了,代码后面也有,省略掉复制数据的操作就好
                return;
            }
            cursor.close();

            // step 4:把旧表数据备份到新表中
            db.execSQL("insert into " + TB_NAME + " select *,' ' from " + tempTableName + ";");

            // step 5:把旧表数据备份到新表中
            db.execSQL("drop table " + tempTableName);

        }
    }

降级表,删除userid字段


    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion == 1 && newVersion == 2) {

            // step 1:获取新表所有信息
            Cursor cursor = db.rawQuery("select * from " + TB_NAME, null);

            // step 2:更改新表未临时表
            String tempTableName = "_temp_" + TB_NAME;
            db.execSQL("alter table " + TB_NAME + " rename to " + tempTableName);

            // step 3:创建原表
            db.execSQL(SQL);
            if (cursor == null) {
                // 如果游标为空,说明旧表中没有数据,如果是这种情况那就可以直接改表的字段,不需要转移数据了,代码后面也有,省略掉复制数据的操作就好
                return;
            }
            cursor.close();

            // step 4:把旧表数据备份到新表中
            db.execSQL("insert into " + TB_NAME + " select 'isSystem','appname',/*'userid',*/'packageName','versionName','versionCode','launcherlist','appIcon','appDir' from " + tempTableName + ";");

            // step 5:把旧表数据备份到新表中
            db.execSQL("drop table " + tempTableName);
        }
    }

App信息bean

public class AppInfo {
    private CharSequence appName;
    private CharSequence packageName;
    private CharSequence versionName;
    private int versionCode = 0;
    private List<String> launcherlist;
    private Drawable appIcon = null;
    private CharSequence appDir;

    public void cleanHight() {
        setAppName(getAppName().toString());
        setPackageName(getPackageName().toString());
        setVersionName(getVersionName().toString());
        setAppDir(getAppDir().toString());
    }

    public void addLauncher(String luncher) {
        if (launcherlist == null) {
            launcherlist = new ArrayList<>();
        }
        if (!launcherlist.contains(luncher)) {
            launcherlist.add(luncher);
        }
    }

    public List<String> getLauncherlist() {
        return launcherlist;
    }

    public void addLauncher(List<String> luncher) {
        if (launcherlist == null) {
            launcherlist = new ArrayList<>();
        }
        launcherlist.clear();
        launcherlist.addAll(luncher);
    }

    public void setVersionName(CharSequence versionName) {
        this.versionName = versionName;
    }

    public void setVersionCode(int versionCode) {
        this.versionCode = versionCode;
    }

    public void setPackageName(CharSequence packageName) {
        this.packageName = packageName;
    }

    public void setAppName(CharSequence appName) {
        this.appName = appName;
    }

    public void setAppIcon(Drawable appIcon) {
        this.appIcon = appIcon;
    }

    public void setAppDir(CharSequence appDir) {
        this.appDir = appDir;
    }

    public CharSequence getAppDir() {
        if(appDir==null){
            return "NULL";
        }
        return appDir;
    }

    public int getVersionCode() {
        return versionCode;
    }

    public Drawable getAppIcon() {
        return appIcon;
    }

    public CharSequence getAppName() {
        if(appName==null){
            return "NULL";
        }
        return appName;
    }

    public CharSequence getPackageName() {
        if(packageName==null){
            return "NULL";
        }
        return packageName;
    }

    public CharSequence getVersionName() {
        if(versionName==null){
            return "NULL";
        }
        return versionName;
    }

    @Override
    public String toString() {
        StringBuilder sb=new StringBuilder();
        if(launcherlist!=null&&launcherlist.size()>0){
            for(String l:launcherlist){
                sb.append("\n    "+l);
            }
        }
        return "应用名称:" +appName+
                "\n  包名:" +packageName+
                "\n  启动Activity:" +sb.toString()+
                "\n  路径:" +appDir+
                "\n  版本信息:"+versionName+"["+versionCode+"]";
    }
}
发布了67 篇原创文章 · 获赞 42 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/w1764662543/article/details/99983192