Android 数据库 使用实例

MyDatabaseHelper.java 的内容如下:

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

/**
 * Created by toby on 17-12-28.
 */

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 static final String CREATE_CATEGORY = "create table Category (" +
            "id integer primary key autoincrement, " +
            "category_name text, " +
            "category_code integer)";

    private Context mContext;

    public MyDatabaseHelper(Context context, String name, 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_SHORT).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        switch (oldVersion) {
            case 1:
                sqLiteDatabase.execSQL(CREATE_CATEGORY);
                // 不要加 break,以保证每次数据库的修改都会被执行
                // break;
            case 2:
                sqLiteDatabase.execSQL("alter table Book add column category_id integer");
                // 不要加 break,以保证每次数据库的修改都会被执行
                // break;
            default:
        }
    }
}

使用的实例代码如下:

import android.app.Activity;
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;

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";
    private MyDatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void create(View view) {
        dbHelper.getWritableDatabase();
    }

    public void add(View view) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", "The first");
        values.put("author", "None");
        values.put("pages", 123);
        values.put("price", 12.34);
        // 第二个参数用于在未指定添加数据的情况下给某些可为空的列自动赋值 NULL,一般填 null
        db.insert("Book", null, values);

        values.clear();

        values.put("name", "The Second");
        values.put("author", "None");
        values.put("pages", 234);
        values.put("price", 23.45);
        db.insert("Book", null, values);
    }

    public void update(View view) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("price","10.00");
        // 不指定,第三和第四个参数,将会更新所有行
        db.update("Book", values, "name = ?", new String[] {"The first"});
    }

    public void delete(View view) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        // 第二个和第三个参数如果不指定将会删除所有行
        db.delete("Book", "pages > ?", new String[] {"200"});
    }

    public void query(View view) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.query("Book", null, null, null,
                null, null, null);

        if (cursor.moveToFirst()) {
            do {
                String value = cursor.getString(cursor.getColumnIndex("name"));
                Log.d(TAG, "Book name is " + value);

                value = cursor.getString(cursor.getColumnIndex("author"));
                Log.d(TAG, "Book author is " + value);

                value = cursor.getString(cursor.getColumnIndex("pages"));
                Log.d(TAG, "Book pages is " + value);

                value = cursor.getString(cursor.getColumnIndex("price"));
                Log.d(TAG, "Book price is " + value);
            } while (cursor.moveToNext());

            cursor.close();
        }
    }

    public void replace(View view) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            db.delete("Book", null, null);
//            if (true) { // 抛出一个异常测试事务
//                throw new NullPointerException();
//            }
            ContentValues values = new ContentValues();
            values.put("name", "The Third");
            values.put("author", "Toby");
            values.put("pages", 720);
            values.put("price", 23.45);
            db.insert("Book", null, values);
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
        }
    }
}

布局文件的代码如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.syberos.learnandroid.MainActivity">

    <Button
        android:id="@+id/create"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="136dp"
        android:layout_marginTop="22dp"
        android:text="@string/create"
        android:onClick="create"
        />

    <Button
        android:id="@+id/add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/create"
        android:layout_below="@+id/create"
        android:layout_marginTop="17dp"
        android:onClick="add"
        android:text="@string/add"
        />

    <Button
        android:id="@+id/update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/add"
        android:layout_below="@+id/add"
        android:layout_marginTop="11dp"
        android:onClick="update"
        android:text="@string/update" />

    <Button
        android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/update"
        android:layout_below="@+id/update"
        android:layout_marginTop="15dp"
        android:onClick="delete"
        android:text="@string/delete" />

    <Button
        android:id="@+id/query"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/delete"
        android:layout_below="@+id/delete"
        android:layout_marginTop="14dp"
        android:text="@string/query"
        android:onClick="query"
        />

    <Button
        android:id="@+id/replace"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/query"
        android:layout_below="@+id/query"
        android:text="@string/replace"
        android:onClick="replace"
        />


</RelativeLayout>

string 文件的内容如下:

<resources>
    <string name="app_name">LearnAndroid</string>
    <string name="create">create</string>
    <string name="add">add</string>
    <string name="update">update</string>
    <string name="delete">delete</string>
    <string name="query">query</string>
    <string name="replace">replace</string>
</resources>

本文参考自 《Android 第一行代码》

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,139评论 25 709
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,695评论 0 17
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,180评论 19 139
  • 看到春妮在朋友圈里发了一条状态,"为何要这么拼命,好累,能不能歇歇。" 春妮在地铁做工程师,最近地铁刚刚试运行,每...
    南风的故事阅读 358评论 1 0
  • 为什么要初始化CSS? 建站老手都知道,这是为了考虑到浏览器的兼容问题,其实不同浏览器对有些标签的默认值是不同的,...
    George2016阅读 14,442评论 0 19