赞
踩
SQLiteOpenHelper基本用法
新建一个 DatabaseTest 项目:
创建一个名为BookStore.db的数据库,然后在这个数据库中新建一张 Book 表,表中有 id(主键)、作者、价格、页数和书名等列。创建数据库表需要用建表语句,Book建表语句如下所示:
- create table Book (
- id integer primary key autoincrement,
- author text,
- price real,
- pages integer,
- name text)
SQLite 不像其他的数据库拥有众多繁杂的数据类型,它的数据类型很简单,integer 表示整型,real 表示浮点型,text 表示文本类型,blob 表示二进制类型。另外,上述建表语句中我们还 使用了 primary key 将 id 列设为主键,并用 autoincrement 关键字表示 id 列是自增长的。
然后需要在代码中执行这条 SQL 语句,才能完成创建表的操作。新建 MyDatabaseHelper 类继承自 SQLiteOpenHelper,代码如下所示:
- package com.example.databasetest;
-
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- import android.widget.Toast;
- import androidx.annotation.Nullable;
-
- public class MyDataBaseHelper extends SQLiteOpenHelper {
- //建表语句, 定义成一个字符串常量
- public static final String CREATE_BOOK = "create table Book (" +
- "id integer primary key autoincrement," +
- "author text," +
- "price real," +
- "pages integer," +
- "name text)";
- private Context mContext;
-
- 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 db) {
- //执行建表语句
- db.execSQL(CREATE_BOOK);
- Toast.makeText(mContext, "Create successfully", Toast.LENGTH_SHORT).show();
- }
-
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
-
- }
- }

在 onCreate()方法中调用 了 SQLiteDatabase 的 execSQL()方法去执行这条建表语句,这样就可以保证在数据库创建完成的同时还能成功创建 Book 表。
修改 activity_main.xml 中的代码,添加一个建表按钮,如下所示:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
-
-
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/create_database"
- android:textAllCaps="false"
- android:text="Create database" />
-
- </LinearLayout>
修改MainActivity如下:
- package com.example.databasetest;
-
- import androidx.appcompat.app.AppCompatActivity;
- import android.os.Bundle;
- import android.widget.Button;
-
- public class MainActivity extends AppCompatActivity {
- private MyDataBaseHelper myDataBaseHelper;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- //新建一个MyDataBaseHelper对象
- myDataBaseHelper = new MyDataBaseHelper(this, "BookStore.db",
- null, 1);
- //新建按钮对象并确立点击事件
- Button buttonCreateDataBase = findViewById(R.id.create_database);
- buttonCreateDataBase.setOnClickListener(v -> {
- //getWritableDatabase会调用MyDataBaseHelper对象的onCreate()方法
- myDataBaseHelper.getWritableDatabase();
- });
- }
- }

点击Create database按钮,会在/data/data/com.example.databasetest/生成databases目录并在该目录中生成BookStore.db数据库文件
在 onCreate()方法中构建了一个 MyDatabaseHelper 对象,并且通过构造函数的参数将数据库名指定为 BookStore.db,版本号指定为 1,然后在 Create database 按钮的点击事件里调用了 getWritableDatabase()方法。这样当第一次点击 Create database按钮时,就会检测到当前程序中没有 BookStore.db这个数据库,于是会创建该数据库并调用 MyDatabaseHelper 中的 onCreate()方法,这样 Book 表也就得到了创建,然后会弹出一个 Toast 提示创建成功。 再次点击 Create database 按钮时,会发现此时已经存在 BookStore.db 数据库了,因此不会再创建一次。
onUpgrade() 方法是用于对数据库进行升级的,它在整个数据库的管理工作当中起着非常重要的作用。
MyDataBaseHelper.java
- package com.example.databasetest;
-
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- import android.util.Log;
- import android.widget.Toast;
- import androidx.annotation.Nullable;
-
- public class MyDataBaseHelper extends SQLiteOpenHelper {
- private static final String TAG = "MyDataBaseHelper";
-
- //建表语句, 定义成一个字符串常量
- public 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;
-
- 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 db) {
- db.execSQL(CREATE_BOOK);
- db.execSQL(CREATE_CATEGORY);
- Toast.makeText(mContext, "Create successfully", Toast.LENGTH_SHORT).show();
- }
-
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- Log.d(TAG, "onUpgrade: Upgrade succeeded");
- db.execSQL("drop table if exists Book");
- db.execSQL("drop table if exists Category");
- onCreate(db);
- }
- }

MainActivity.java
- package com.example.databasetest;
-
- import androidx.appcompat.app.AppCompatActivity;
-
- import android.content.ContentValues;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
-
-
- public class MainActivity extends AppCompatActivity {
- private static final String TAG = "MainActivity";
-
- private MyDataBaseHelper myDataBaseHelper;
- private SQLiteDatabase database;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- //新建一个MyDataBaseHelper对象
- myDataBaseHelper = new MyDataBaseHelper(this, "BookStore.db",
- null, 3);
- //新建按钮对象并确立点击事件
- Button buttonCreateDataBase = findViewById(R.id.create_database);
- buttonCreateDataBase.setOnClickListener(v -> {
- //getWritableDatabase会调用onCreate()方法
- myDataBaseHelper.getWritableDatabase();
- });
-
- //添加数据
- Button addDataButton = findViewById(R.id.add_data);
- addDataButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Log.d(TAG, "--------------------Add Data--------------------");
- database = myDataBaseHelper.getWritableDatabase();
- ContentValues contentValues = new ContentValues();
- //第一条数据, 添加完成后要清除ContentValues里面的内容
- contentValues.put("author", "AAA");
- contentValues.put("price", "16");
- contentValues.put("pages", 200);
- contentValues.put("name", "AAA's book");
- database.insert("Book", null, contentValues);
- contentValues.clear();
- //第二条数据
- contentValues.put("author", "BBB");
- contentValues.put("price", 10);
- contentValues.put("pages", 300);
- contentValues.put("name", "BBB's book");
- database.insert("Book", null, contentValues);
- contentValues.clear();
- //第三条数据
- contentValues.put("author", "CCC");
- contentValues.put("price", 16);
- contentValues.put("pages", 500);
- contentValues.put("name", "CCC's book");
- database.insert("Book", null, contentValues);
- contentValues.clear();
- }
- });
-
- //更改数据
- Button updateDataButton = findViewById(R.id.update_data);
- updateDataButton.setOnClickListener(v -> {
- Log.d(TAG, "--------------------Update Data--------------------");
- database = myDataBaseHelper.getWritableDatabase();
- ContentValues contentValues = new ContentValues();
- contentValues.put("price", 100.8);
- database.update("Book", contentValues, "author=?", new String[] {"BBB"});
- database.update("Book", contentValues, "author=?", new String[] {"CCC"});
- });
-
- //删除数据
- Button deleteDataButton = findViewById(R.id.delete_data);
- deleteDataButton.setOnClickListener(v -> {
- Log.d(TAG, "--------------------Delete Data--------------------");
- database = myDataBaseHelper.getWritableDatabase();
- database.delete("Book", "pages <= ?", new String[] {"200"});
- });
-
- //查询数据
- Button queryDataButton = findViewById(R.id.query_data);
- queryDataButton.setOnClickListener(v -> {
- Log.d(TAG, "--------------------Query Data--------------------");
- database = myDataBaseHelper.getWritableDatabase();
- Cursor cursor = database.query("Book", null, null, null, null, null, null);
- if (cursor.moveToFirst()) {
- do {
- String author = cursor.getString(cursor.getColumnIndexOrThrow("author"));
- String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
- int pages = cursor.getInt(cursor.getColumnIndexOrThrow("pages"));
- double price = cursor.getDouble(cursor.getColumnIndexOrThrow("price"));
- Log.d(TAG, " author: " + author + " name: " + name + " pages: " + pages + " price: " + price);
- } while (cursor.moveToNext());
- }
- cursor.close();
- });
- }
- }

activity_main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
-
-
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/create_database"
- android:textAllCaps="false"
- android:text="Create database" />
-
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/add_data"
- android:text="Add Data"
- android:textAllCaps="false"
- />
-
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/update_data"
- android:text="Update Data"
- android:textAllCaps="false"
- />
-
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/delete_data"
- android:text="Delete Data"
- android:textAllCaps="false"
- />
-
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/query_data"
- android:text="Query Data"
- android:textAllCaps="false"
- />
-
- </LinearLayout>

界面如下:
待更......
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。