天天看點

Android SQLite資料庫(具體例子)

Android SQLite資料庫

1.基本概念

參考自:https://www.runoob.com/w3cnote/android-tutorial-sqlite-intro.html

  1. SQLite是一個輕量級的關系型資料庫,運算速度快,占用資源少,很适合在移動裝置上使用, 不僅支援标準SQL文法,還遵循ACID(資料庫事務)原則,無需賬号,使用起來非常友善!
  2. 前面我們學習了使用檔案與SharedPreference來儲存資料,但是在很多情況下, 檔案并不一定是有效的,如多線程并發通路是相關的;app要處理可能變化的複雜資料結構等等! 比如銀行的存錢與取錢!使用前兩者就會顯得很無力或者繁瑣,資料庫的出現可以解決這種問題, 而Android又給我們提供了這樣一個輕量級的SQLite,為何不用?
  3. SQLite支援五種資料類型:NULL,INTEGER,REAL(浮點數),TEXT(字元串文本)和BLOB(二進制對象) 雖然隻有五種,但是對于varchar,char等其他資料類型都是可以儲存的;因為SQLite有個最大的特點: 你可以各種資料類型的資料儲存到任何字段中而不用關心字段聲明的資料類型是什麼,比如你 可以在Integer類型的字段中存放字元串,當然除了聲明為主鍵INTEGER PRIMARY KEY的字段隻能夠存儲64位整數! 另外, SQLite 在解析CREATE TABLE 語句時, 會忽略 CREATE TABLE 語句中跟在字段名後面的資料類型資訊如下面語句會忽略 name字段的類型資訊: CREATE TABLE person (personid integer primary key autoincrement, name varchar(20))

相關類:

  • SQLiteOpenHelper:抽象類,我們通過繼承該類,然後重寫資料庫建立以及更新的方法, 我們還可以通過該類的對象獲得資料庫執行個體,或者關閉資料庫!
  • SQLiteDatabase:資料庫通路類:我們可以通過該類的對象來對資料庫做一些增删改查的操作
  • Cursor:遊标,有點類似于JDBC裡的resultset,結果集!可以簡單了解為指向資料庫中某 一個記錄的指針!

2.相關例子

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:background="@drawable/bg"
    android:orientation="vertical"
    >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="200dp"
    android:layout_marginLeft="50dp">
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="姓 名:"
        android:textSize="30sp"
     />

    <EditText
        android:id="@+id/et_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="請輸入姓名"
        android:textSize="20sp"
        >
    </EditText>
</LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginLeft="50dp">
        <TextView
            android:id="@+id/phone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="電 話:"
            android:textSize="30sp"
            />

        <EditText
            android:id="@+id/et_phone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="請輸入手機号碼"
            android:textSize="20sp"
            >
        </EditText>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        >
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="添加"
            android:id="@+id/btn_add"
            android:textSize="18sp"
            android:background="#8F92EE"
            >

        </Button>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="查詢"
            android:id="@+id/btn_query"
            android:textSize="18sp"
            android:background="#9D66A8"
            >

        </Button>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="修改"
            android:id="@+id/btn_update"
            android:textSize="18sp"
            android:background="#F9ACFF"
            >

        </Button>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="删除"
            android:id="@+id/btn_delete"
            android:textSize="18sp"
            android:background="#ACD6FF"
            >
        </Button>

    </LinearLayout>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/show"
        android:textSize="20sp"
        android:layout_marginTop="20dp"
        android:textColor="#04F11C">

    </TextView>
</LinearLayout>
           

MainActivity.java

package com.example.directory;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import static com.example.directory.R.id.btn_add;
import static com.example.directory.R.id.name;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_name;
    private EditText et_phone;
    private TextView show;
    private Button btn_add;
    private Button btn_query;
    private Button btn_delete;
    private Button btn_update;
    private MyHelper myHelper;
    private String name;
    private String phone;
    private SQLiteDatabase db;
    private ContentValues values;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myHelper = new MyHelper(this);
        init();
    }

    private void init() {
        et_name = (EditText)findViewById(R.id.et_name);
        et_phone = (EditText)findViewById(R.id.et_phone);
        show = (TextView)findViewById(R.id.show);
        btn_add = (Button)findViewById(R.id.btn_add);
        btn_query = (Button)findViewById(R.id.btn_query);
        btn_delete = (Button)findViewById(R.id.btn_delete);
        btn_update = (Button)findViewById(R.id.btn_update);
        btn_update.setOnClickListener(this);
        btn_delete.setOnClickListener(this);
        btn_add.setOnClickListener(this);
        btn_query.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_add: //添加資料
                name = et_name.getText().toString();
                phone = et_phone.getText().toString();
                db = myHelper.getReadableDatabase();//擷取可讀資料庫對象

                values = new ContentValues();
                values.put("name",name);
                values.put("phone",phone);
                db.insert("information",null,values);
                db.close();

                break;
            case R.id.btn_query: //查詢資料
                db = myHelper.getReadableDatabase();
                Cursor cursor = db.query("information",null,null,null,null,null,null);
                if (cursor.getCount() == 0){
                    show.setText("");
                    Toast.makeText(this,"沒有資料",Toast.LENGTH_LONG).show();
                }else{
                    cursor.moveToFirst();
                    show.setText("Name:"+cursor.getString(1)+"     Tel:"+cursor.getString(2));
                }

                while (cursor.moveToNext()){
                    show.append("\n"+"Name:"+cursor.getString(1)+"     Tel:"+cursor.getString(2));
                }
                cursor.close();
                db.close();

                break;

            case R.id.btn_update: //更新資料
                db = myHelper.getWritableDatabase();
                values = new ContentValues();
                values.put("phone",phone=et_phone.getText().toString());
                db.update("information",values,"name=?",new  String[]{et_name.getText().toString()});
                db.close();

                break;
            case R.id.btn_delete: //删除資料
                db = myHelper.getWritableDatabase();
                db.delete("information",null,null);
                Toast.makeText(this,"資訊已經删除",Toast.LENGTH_LONG).show();
                show.setText("");
                db.close();

                break;
        }
    }
}
           

MyHelper.java

package com.example.directory;

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

public class MyHelper extends SQLiteOpenHelper {

    public MyHelper(Context context){
        super(context,"itcast.db",null,1);
    }

    //當資料庫第一次建立的時候執行
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE information (_id INTEGER PRIMARY KEY AUTOINCREMENT ,name VAECHAR(20) ,phone VARCHAR(20))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}
           

運作截圖:

點選添加後查詢:

Android SQLite資料庫(具體例子)

密碼重新輸入後點選修改後查詢:

Android SQLite資料庫(具體例子)

點選删除後查詢:

Android SQLite資料庫(具體例子)