zoukankan      html  css  js  c++  java
  • Android数据存储引擎---SQLite数据库

    目标:是否可以在PC端桌面上使用SQLite数据库制作一个财务文件?

    目录:

    来源:

    实践:

    总结和比较:

    SQLite数据简介

        是什么,内部结构是怎样的,数据库和表的关系是什么

        有什么用

        常用的操作是什么

    SQLite数据库使用

        增

        删

        改

        查

    SQLite数据库实践上的优化措施

    对于Android平台来说,系统内置了丰富的API来供开发人员操作SQLite,使我们轻松完成对数据的存取。

    步骤1,熟悉创建数据库表,熟悉相关的操作指令,实现对SQLite数据库的感性认识

    创建一个包含简单内容的数据库(数据库名)和对应的表(表名);创建表后,可执行简单的“增删改查”指令。

        /**
         * <功能描述> 初始化数据库,创建数据库
         * 
         * @return void [返回类型说明]
         */
        private void initDataBase() {
            mDatabase = openOrCreateDatabase("SqlDemo.db", Context.MODE_PRIVATE,
                    null);
            // CREATE_TABLE = "CREATE TABLE person (_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age SMALLINT)";
            mDatabase.execSQL(CREATE_TABLE);
        }

    创建数据库的操作调用了execSQL(...),参数代表的是创建数据库指令,其结果会在/data/data/packageName/databases/目录下生成对应的数据库文件,同时执行了在数据库中创建了person的数据表。

    步骤2,在数据库中创建数据表,并执行相关的基本操作

        /**
         * <功能描述> 执行一些数据库和表的操作
         * 
         * @return void [返回类型说明]
         */
        private void doSomeAction() {
            Person person = new Person("john", 30);
            mDatabase.execSQL("INSERT INTO person VALUES (NULL, ?, ?)",
                    new Object[] {
                            person.getName(), person.getAge()
                    });
            person.setName("David");
            person.setAge(33);
            ContentValues cv = new ContentValues();
            cv.put("name", person.getName());
            cv.put("age", person.getAge());
            mDatabase.insert("person", null, cv);
            cv = new ContentValues();
            cv.put("age", 35);
            mDatabase.update("person", cv, "name=?", new String[] {
                "john"
            });
            Cursor cursor = mDatabase.rawQuery(
                    "SELECT * FROM person WHERE age >= ?", new String[] {
                        "33"
                    });
            while (cursor != null && cursor.moveToFirst()) {
                int _id = cursor.getInt(cursor.getColumnIndex("_id"));
                String name = cursor.getString(cursor.getColumnIndex("name"));
                int age = cursor.getInt(cursor.getColumnIndex("age"));
                Log.d(TAG, "_id>=" + _id + ", name=>" + name + ", age=>" + age);
            }
            cursor.close();
            mDatabase.delete("person", "age<?", new String[] {
                "35"
            });
            mDatabase.close();
        }

    粗略地区分对数据库的操作,有以下两种:数据库操作、数据库中数据表的操作。

    对于数据库中数据表的操作中,添加、删除和更新可以使用下述两种方式:

    public void execSQL(String sql) throws SQLException;
    public void execSQL(String sql, Object[] bindArgs) throws SQLException;

    上述可以认为是一种统一的形式,执行的是传统数据库操作的指令。

    此外,还有对应的可供区分的API方法:

    public long insert(String table, String nullColumnHack, ContentValues values);
    public int update(String table, ContentValues values, String whereClause, String[] whereArgs);
    public int delete(String table, String whereClause, String[] whereArgs);

    参数中的table都表示对应数据库中对应table;ContentValues实例values如下内容:

    /** Holds the actual values */
    private HashMap<String, Object> mValues;

    其中Key表示的列名,Values表示的是待写入的内容。参数String whereClause表示WHERE表达式,而String[]则为上述对应占位符的实际参数值。

    查询语句相对来说较为复杂,因为工程问题中经常会面对各种各样的查询问题,系统也考虑到了这种复杂性,为我们提供了较为丰富的查询形式:

    public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
    public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
    public Cursor query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
    public Cursor query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal)
    public Cursor queryWithFactory(CursorFactory cursorFactory, boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
    public Cursor queryWithFactory(CursorFactory cursorFactory, boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal)

    此外还有如下四种粗略查询方式:

    public Cursor rawQuery(String sql, String[] selectionArgs)
    public Cursor rawQuery(String sql, String[] selectionArgs, CancellationSignal cancellationSignal)
    public Cursor rawQueryWithFactory(CursorFactory cursorFactory, String sql, String[] selectionArgs, String editTable)
    public Cursor rawQueryWithFactory(CursorFactory cursorFactory, String sql, String[] selectionArgs, String editTable, CancellationSignal cancellationSignal)

    其中sql字符串,表示一个SQL语句,可以使用占位符代替实际值;而selectionArgs就是占位符的实际参数集合;columns表示要查询的列的所有名称集合;selection表示WHERE之后的条件语句,可以使用占位符。

    上述API都会返回Cursor实例,代表数据集的游标。

    SQL数据库的灵活使用,更多的是在查询语句中,包含更多的技巧和方法;因为这也是Android UI展示的内容来源。

    Cursor的可用方法如下:

    c.move(int offset); //以当前位置为参考,移动到指定行  
    c.moveToFirst();    //移动到第一行  
    c.moveToLast();     //移动到最后一行  
    c.moveToPosition(int position); //移动到指定行  
    c.moveToPrevious(); //移动到前一行  
    c.moveToNext();     //移动到下一行  
    c.isFirst();        //是否指向第一条  
    c.isLast();     //是否指向最后一条  
    c.isBeforeFirst();  //是否指向第一条之前  
    c.isAfterLast();    //是否指向最后一条之后  
    c.isNull(int columnIndex);  //指定列是否为空(列基数为0)  
    c.isClosed();       //游标是否已关闭  
    c.getCount();       //返回总数据项数(行数)  
    c.getPosition();    //返回当前游标所指向的行数  
    c.getColumnIndex(String columnName);//返回某列名对应的列索引值  
    c.getString(int columnIndex);   //返回当前行指定列的值  

    获取内容则是使用如下API:

    byte[] getBlob(int columnIndex);
    String getString(int columnIndex);
    short getShort(int columnIndex);
    int getInt(int columnIndex);
    long getLong(int columnIndex);
    float getFloat(int columnIndex);
    double getDouble(int columnIndex);

    步骤3:实际开发对上述操作做改进,以更方便开发流程。

    在实际开发中,为了更好地管理和维护数据库,会封装一个继承自SQLiteOpenHelper类的数据库操作管理类,然后以这个类为基础再封装自己的业务逻辑。

    A helper class to manage database creation and version management.
  • 相关阅读:
    解决MyBatis的Mapper XML错误,系统起不来,也不报错问题
    tomcat启动卡在“INFO com.alibaba.druid.pool.DruidDataSource
    加速github访问速度
    LAN、WAN和WLAN的区别
    面试记录一
    C++纯虚函数(接口类)的使用
    CentOS 安装 Docker CE
    通过 plsql 连接远程 Oracle
    Yum 软件仓库配置
    qW3xT.2,解决挖矿病毒
  • 原文地址:https://www.cnblogs.com/CVstyle/p/6388166.html
Copyright © 2011-2022 走看看