Android 數(shù)據(jù)庫 使用實(shí)例

MyDatabaseHelper.java 的內(nèi)容如下:

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脂男,以保證每次數(shù)據(jù)庫的修改都會被執(zhí)行
                // break;
            case 2:
                sqLiteDatabase.execSQL("alter table Book add column category_id integer");
                // 不要加 break,以保證每次數(shù)據(jù)庫的修改都會被執(zhí)行
                // break;
            default:
        }
    }
}

使用的實(shí)例代碼如下:

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);
        // 第二個參數(shù)用于在未指定添加數(shù)據(jù)的情況下給某些可為空的列自動賦值 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");
        // 不指定休涤,第三和第四個參數(shù)文兑,將會更新所有行
        db.update("Book", values, "name = ?", new String[] {"The first"});
    }

    public void delete(View view) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        // 第二個和第三個參數(shù)如果不指定將會刪除所有行
        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) { // 拋出一個異常測試事務(wù)
//                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 文件的內(nèi)容如下:

<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 第一行代碼》

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子园爷,更是在濱河造成了極大的恐慌戴质,老刑警劉巖度宦,帶你破解...
    沈念sama閱讀 211,194評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異告匠,居然都是意外死亡戈抄,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,058評論 2 385
  • 文/潘曉璐 我一進(jìn)店門后专,熙熙樓的掌柜王于貴愁眉苦臉地迎上來划鸽,“玉大人,你說我怎么就攤上這事戚哎÷惴蹋” “怎么了?”我有些...
    開封第一講書人閱讀 156,780評論 0 346
  • 文/不壞的土叔 我叫張陵型凳,是天一觀的道長丈冬。 經(jīng)常有香客問我,道長甘畅,這世上最難降的妖魔是什么埂蕊? 我笑而不...
    開封第一講書人閱讀 56,388評論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮疏唾,結(jié)果婚禮上蓄氧,老公的妹妹穿的比我還像新娘。我一直安慰自己槐脏,他們只是感情好喉童,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,430評論 5 384
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著准给,像睡著了一般泄朴。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上露氮,一...
    開封第一講書人閱讀 49,764評論 1 290
  • 那天祖灰,我揣著相機(jī)與錄音,去河邊找鬼畔规。 笑死局扶,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播三妈,決...
    沈念sama閱讀 38,907評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼畜埋,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了畴蒲?” 一聲冷哼從身側(cè)響起悠鞍,我...
    開封第一講書人閱讀 37,679評論 0 266
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎模燥,沒想到半個月后咖祭,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,122評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蔫骂,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,459評論 2 325
  • 正文 我和宋清朗相戀三年么翰,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片辽旋。...
    茶點(diǎn)故事閱讀 38,605評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡浩嫌,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出补胚,到底是詐尸還是另有隱情码耐,我是刑警寧澤,帶...
    沈念sama閱讀 34,270評論 4 329
  • 正文 年R本政府宣布溶其,位于F島的核電站伐坏,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏握联。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,867評論 3 312
  • 文/蒙蒙 一每瞒、第九天 我趴在偏房一處隱蔽的房頂上張望金闽。 院中可真熱鬧,春花似錦剿骨、人聲如沸代芜。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,734評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽挤庇。三九已至,卻和暖如春贷掖,著一層夾襖步出監(jiān)牢的瞬間嫡秕,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,961評論 1 265
  • 我被黑心中介騙來泰國打工苹威, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留昆咽,地道東北人。 一個月前我還...
    沈念sama閱讀 46,297評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像掷酗,于是被迫代替她去往敵國和親调违。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,472評論 2 348

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 171,747評論 25 707
  • ¥開啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程泻轰,因...
    小菜c閱讀 6,365評論 0 17
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理技肩,服務(wù)發(fā)現(xiàn),斷路器浮声,智...
    卡卡羅2017閱讀 134,629評論 18 139
  • 看到春妮在朋友圈里發(fā)了一條狀態(tài)虚婿,"為何要這么拼命,好累阿蝶,能不能歇歇雳锋。" 春妮在地鐵做工程師,最近地鐵剛剛試運(yùn)行羡洁,每...
    南風(fēng)的故事閱讀 322評論 1 0
  • 為什么要初始化CSS玷过? 建站老手都知道,這是為了考慮到瀏覽器的兼容問題筑煮,其實(shí)不同瀏覽器對有些標(biāo)簽的默認(rèn)值是不同的辛蚊,...
    George2016閱讀 14,364評論 0 19