阅读 53

SQLiteOpenHelper

Android为了我们能更加方便的管理数据库,专门提供了一个SQLiteOpenHelper帮助类,借助这个类我们可以非常简单的对数据库进行创建和升级。

创建SQLiteOpenHelper帮助类

SQLiteOpenHelper是一个抽象类,如果我们要使用它的话,就需要创建一个自己的帮助类去继承它。SQLiteOpenHelper有两个抽象方法,分别是onCrete()和onUpgrade(),我们必须在自己的帮助类里面重写这两个方法,然后分别在这两个方法中去实现创建、升级数据库的逻辑。SQLiteOpenHelper中还有两个非常重要的实例方法:getReaderDatabase()和getWritalbeDatabase()。这两个方法都可以创建或者打开一个现有的数据库,并返回一个可对数据库进行读写操作的对象。不同的是,当数据库不可写入的时候,getReaderDatabase()返回的对象将以只读的方式打开数据库,而getWritalbeDatabase()则出现异常。

public class MyDatabaseHelper extends SQLiteOpenHelper {

    private static final String CREATE_BOOK = "create table Book("
            + " id integer primary key autoincrement,"
            + " price real,"
            + " author text,"
            + " pages integer,"
            + " name text)";

    private static final String CREATE_CATEGORY = "create table Category("
            + " id integer primary key autoincrement,"
            + " category_name text,"
            + " category_code integer)";

    private Context mContext;

     /*
       context  上下文
       name     数据库名
       factory  允许我们在查询的时候返回一个自定义的Cursor,一般传入null
       version  当前数据库版本号,可以用于对数据库进行升级操作
    */

    public MyDatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(CREATE_BOOK);
        sqLiteDatabase.execSQL(CREATE_CATEGORY);
        Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_LONG).show();

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("drop table if exists Book");
        sqLiteDatabase.execSQL("drop table if exists Category");
        onCreate(sqLiteDatabase);
    }
}

创建数据库

首先会检测是否存在“BookStore.db” 这个数据库,如果没有,就会创建该数据库并调用myDatabaseHelper中的onCreate(),创建的数据库文件会放在 /data/data/projectName/databases/目录下

MyDatabaseHelper myDatabaseHelper = new MyDatabaseHelper(this, "BookStore.db", null, 1);
myDatabaseHelper.getWritableDatabase();

查看数据库

adb是Android SDK中自带的一个调试工具,使用这个工具可以直接对连接在电脑上的手机或者模拟器进行调试操作。它存放在sdk的platform-tools目录下,如果想要在命令文件中使用这个工具,就需要把platform-tools的路径配置到环境变量Path里面。配置好环境变量以后就可以使用adb工具了。打开命令行界面,输入adb.shell,就会进入到设备的控制台。命令行显示$符号,表示你现在是普遍管理员,需要输入su命令切换到超级管理员,#表示是超级管理员。如果su命令之后无法切换到超级管理员,很有可能是你Android系统的原因,检查一下你模拟器的系统是否是APIs的系统,如果不是,下载一个Google APls镜像系统,使用这个系统的虚拟机再启动项目。再操作之前的命令,切换到超级管理员,接下来用cd命令进入到 /data/data/你的项目名/databases/ 目录下,并使用ls查看该目录里面的文件。这个目录下出现两个文件,一个是我们创建的BookStore.db,而另外一个BookStore.db-journal则是为了让数据库能够支持事务而产生的临时日志文件。接下来我们使用“sqlite3 数据库名”,打开数据库,这里使用sqlite3 BookStore.db打开BookStore数据库。用.table查看有哪些表,用.schema查看建表语句,用.exit退出设备控制台。

升级数据库

最初传的版本号是1,现在传2,表示数据库升级,会调用MyDatabaseHelper的onUpgrade(),在里面执行升级数据库的逻辑,先删除原来存在的数据库,再执行onCreate(),创建相应的几个表。之所以要升级数据库,是因为数据库在已经存在的情况下,不会再执行onCreate(),也就没有办法再创建新的表,所以这里我们升级数据库,先删掉原来的一些表格,再调用onCreate(),代码在MyDatabaseHelper类里。

MyDatabaseHelper myDatabaseHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);
myDatabaseHelper.getWritableDatabase()

添加数据

SQLiteDatabase sqLiteDatabase = myDatabaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", "The Da Vinci Code");
contentValues.put("author", "Dan Brown");
contentValues.put("pages", 452);
contentValues.put("price", 16.96);
sqLiteDatabase.insert("Book", null, contentValues);

contentValues.clear();
//开始装第二条数据
contentValues.put("name", "The Lost Symbol");
contentValues.put("author", "Dan Brown");
contentValues.put("pages", 510);
contentValues.put("price", 19.95);
sqLiteDatabase.insert("Book", null, contentValues);

更新数据

SQLiteDatabase sqLiteDatabase = myDatabaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("price", 10.99);
sqLiteDatabase.update("Book", contentValues, "name = ?",new String[]{"The Da Vinci Code"});

删除数据

SQLiteDatabase sqLiteDatabase = myDatabaseHelper.getWritableDatabase();
sqLiteDatabase.delete("Book", "pages > ?", new String[]{"500"});

查询数据

SQLiteDatabase sqLiteDatabase = myDatabaseHelper.getWritableDatabase();
Cursor cursor = sqLiteDatabase.query("Book", null,null, null, null, null, null);
if (cursor.moveToFirst()) {
     do {
@SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("name"));
@SuppressLint("Range") String author = cursor.getString(cursor.getColumnIndex("author"));
@SuppressLint("Range") int pages = cursor.getInt(cursor.getColumnIndex("pages"));
@SuppressLint("Range") double price = cursor.getDouble(cursor.getColumnIndex("price"));
   } while (cursor.moveToNext());
       }
    cursor.close();

使用SQL操作数据库

sqLiteDatabase.execSQL(),可以进行插入、更新和删除,具体不详细描述,自行百度。
sqLiteDatabase.rawQuery(),进行查询。

原文:https://www.cnblogs.com/ngy-liupeng/p/15180911.html

文章分类
代码人生
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐