安卓开发笔记(十二):SQLite数据库储存(上)

SQLite数据库存储(上)

 创建数据库

Android专门提供了一个 SQLiteOpenHelper帮助类对数据库进行创建和升级

SQLiteOpenHelper需要创建一个自己的帮助类去继承它并且重写它的两个抽象方法,即 onCreate() 和 onUpgrade()

SQLiteOpenHelper 中有两个重要的实例方法:getReadableDatabase() 和 getWritableDatabase(),第一个方法可以在磁盘空间已满的时候,只读数据,而第二种方法在空间已满的时候,则会出现异常

创建一个名为 BookStore.db 的数据库

在这个数据库中新建一张 book表,表中有 id(主键)、作者、价格、页数和书名等列

我们在我们的项目当中新建 MyDatabaseHelper类,并继承自 SQLiteOpenHelper,后面则可以在我们的主活动当中启用这段新建的代码,这个类的代码如下:

package com.example.lenovo.studyittwo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

public class MyDatabaseHelper extends SQLiteOpenHelper {
    private static final String CREATE_BOOK = "create table book("
            +"id integer primary key autoincrement,"
            +"author text,"
            +"price real,"
            +"pages integer,"
            +"name text)";

    private Context mContext;//至于为什么我们要使用下面这段代码以及为什么要定义这个私有的变量,书上并没有写我也不知道

    /**
     * 构造方法
     * @param context
     * @param name 数据库名
     * @param factory 允许我们在查询数据的时候返回一个自定义的 Cursor,一般都是传入 null
     * @param version 当前数据库的版本号,可用于对数据库进行升级操作
     */
    public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }

    /**
     * 创建数据库
     * @param db
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
//SQLiteDatabase这个数据库是本身就存在的,并不需要我们自己去写,因为在前面的代码当中我们已经进行了import操作
// 执行建表语句 db.execSQL(CREATE_BOOK); Toast.makeText(mContext,"创建数据库功",Toast.LENGTH_LONG).show(); } /** * 升级数据库 * @param db * @param oldVersion * @param newVersion */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }

下面是主活动的代码。也十分容易理解,我们在一个按钮的事件当中加入主活动与这个类相联系的函数就可以了:

package com.example.lenovo.studyittwo;


import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private MyDatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 构建MyDatabaseHelper对象,指定数据库名为"BookStore.db、版本号为1
        dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 1);

        Button btn_create_database = (Button) findViewById(R.id.creat);
        btn_create_database.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 创建或打开一个现有的数据库(已存在则打开,否则创建一个新的)虽然这很显然,但是我们怎么创建或者打开自己所指定的数据库呢?难道就只能够打开我们刚刚创建的这一个数据库吗?
                dbHelper.getWritableDatabase();
            }
        });


    }}

下面是我们主界面的代码,只需要创建一个按钮就可以了:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

   <Button
       android:id="@+id/creat"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Creat database"/>

</android.support.constraint.ConstraintLayout>

最后,我们只需要按住这个按钮,界面上就会弹出“数据库创建成功”的toast资阳区,再次点击的时候就不会出现了,但我们可以使用另外的的方法来查看我们创建数据库成功没,打开cmd就可以很容易地查看了。

 二.往数据库当中再添加新表的方法

假设我们往数据库当中加入category这张表的话,代码首先从我们刚刚创建的类里在添加一段创建表的代码就可以了,同时在建表语句onCreate函数下添加建表语句

 db.execSQL(CREATE_CATEGORY);

最后我们在

 onUpgrade()方法内写上:
  db.execSQL("drop table if exists Book");
  db.execSQL("drop table if exists Category")
  onCreate(db);

这样子就可以避免我们必须卸载我们的软件才可以在点击create database之后出现“新建数据库成功”的Toast字样。
代码如下:
package com.example.lenovo.studyittwo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

public class MyDatabaseHelper extends SQLiteOpenHelper {
    private static final String CREATE_BOOK = "create table book("
            +"id integer primary key autoincrement,"
            +"author text,"
            +"price real,"
            +"pages integer,"
            +"name text)";

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



    private Context mContext;//至于为什么我们要使用下面这段代码以及为什么要定义这个私有的变量,书上并没有写我也不知道

    /**
     * 构造方法
     * @param context
     * @param name 数据库名
     * @param factory 允许我们在查询数据的时候返回一个自定义的 Cursor,一般都是传入 null
     * @param version 当前数据库的版本号,可用于对数据库进行升级操作
     */
    public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }

    /**
     * 创建数据库
     * @param db
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        // 执行建表语句
        db.execSQL(CREATE_BOOK);
        db.execSQL(CREATE_CATEGORY);
        Toast.makeText(mContext,"创建数据库功",Toast.LENGTH_LONG).show();
    }

    /**
     * 升级数据库
     * @param db
     * @param oldVersion
     * @param newVersion
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists Book");
        db.execSQL("drop table if exists Category");
        onCreate(db);
    }

}

在写完这段代码之后,由于我们使用了

onUpgrade()函数

因此我们在主活动当中对代码进行一定的更改,将主活动当中的
dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 1);
更改成:
dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);
确保后面的版本号为2才可以使用这个升级的函数,具体主活动的代码如下:
package com.example.lenovo.studyittwo;


import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private MyDatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 构建MyDatabaseHelper对象,指定数据库名为"BookStore.db、版本号为1,版本号改为2之后则会直接
        dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);

        Button btn_create_database = (Button) findViewById(R.id.creat);
        btn_create_database.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 创建或打开一个现有的数据库(已存在则打开,否则创建一个新的)
                dbHelper.getWritableDatabase();
            }
        });


    }}

最终就可以得到新表插入成功的结果了。




posted @ 2019-03-13 17:37  Geeksongs  阅读(2568)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

All rights reserved, no one is allowed to pirate or use the document for other purposes.