Android SQLite數據庫的操做CRUD(案例)

一、知識點總結

一、動態添加組件(查詢數據時)
二、對SQLite數據庫的建立以及CRUD的操做
java

二、案例介紹

CRUD:增刪改查android

此案例主要是對數據庫進行CRUD的操做總結。sql

  • 數據庫名:product.db
  • 表名:information
  • 字段:id(integer類型 自增,主鍵), name(varchar(20)),price(integer)

三、佈局文件

頁面展現:
底部數據爲點擊查詢後出現的數據,默認沒有
在這裏插入圖片描述

數據庫

<?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" android:orientation="vertical" tools:context=".SqliteActivity">

    <EditText android:id="@+id/et_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="請輸入Name" />

    <EditText android:id="@+id/et_passwd" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="number" android:hint="請輸入Price" />
    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
    <Button android:id="@+id/bt_insert" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="插入" />
        <Button android:id="@+id/bt_delete" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="刪除" />
        <Button android:id="@+id/bt_update" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="修改" />
        <Button android:id="@+id/bt_select" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="查詢" />
    </LinearLayout>
    
	<!-- 動態添加組件, 查詢時用到 -->
    <LinearLayout android:id="@+id/linearLayoutOut" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"/>
    
</LinearLayout>

四、代碼

4.一、實體類:

Priduct.javaapp

package com.example.sqlitedemo;

import android.content.Intent;

public class Product {
    private int id;
    private String name;
    private int price;

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public Product() {
    }

    public Product(int id, String name, int price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }
}

4.二、建立數據庫

MySqLiteHelper.javaide

package com.example.sqlitedemo;

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


import androidx.annotation.Nullable;

public class MySqLiteHelper extends SQLiteOpenHelper {

    private Context context;
    /** * * 第二個參數: name 數據庫的名字 * 第三個參數: cursorFactory :遊標工廠「對象nu1l * 第四個參數: version 版本號1,2 * * */
    public MySqLiteHelper(@Nullable Context context) {
        super(context, "product.db",null, 1);
        this.context = context;
    }

    /** * 第一次建立數據庫時, 纔會調用 * * 將建表語句寫在這個方法裏。 * */
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE information(" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
                "name VARCHAR(20)," +
                "price INTEGER)");

        Toast.makeText(context, "數據表建立成功",Toast.LENGTH_SHORT).show();
    }

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

    }
}

4.三、CRUD操做

SqliteActivity.java
各個參數具體說明在底部。
佈局

package com.example.sqlitedemo;

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;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SqliteActivity extends AppCompatActivity  {

    private MySqLiteHelper helper;
    private Button bt_insert;
    private Button bt_delete;
    private Button bt_update;
    private Button bt_select;
    private EditText editName;
    private EditText editPasswd;
    private SQLiteDatabase db;
    private ContentValues values;
    private LinearLayout linearLayoutOut;
    private LinearLayout linearLayoutIn;
    private LinearLayout.LayoutParams layoutParams;
    private TextView textName;
    private TextView textPrice;
    private TextView textId;


    /** * 初始化 * */
    public  void init(){
        editName = findViewById(R.id.et_name);
        editPasswd = findViewById(R.id.et_passwd);
        bt_insert = findViewById(R.id.bt_insert);
        bt_delete = findViewById(R.id.bt_delete);
        bt_update = findViewById(R.id.bt_update);
        bt_select = findViewById(R.id.bt_select);
        linearLayoutOut = findViewById(R.id.linearLayoutOut);
        //爲linearLayout設置屬性
        layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
    }

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

        //建立數據表
        helper =  new MySqLiteHelper(this);
        //調用getWritableDatabase() 或getReadableDatabase()建立數據庫
        db = helper.getWritableDatabase();

        /** * 插入數據 * the row ID of the newly inserted row, or -1 if an error occurred * 插入成功返回新的行數, 失敗-1 * * */
        bt_insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                values = new ContentValues();
                //判斷輸入框內是否有值
                if (editName.getText().length() != 0 &&  editPasswd.getText().length() != 0) {
                    values.put("name",editName.getText().toString());
                    values.put("price",editPasswd.getText().toString());
                    long id = db.insert("information", null, values);
                    if (id != -1) {
                        Toast.makeText(SqliteActivity.this,"successful",Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(SqliteActivity.this,"failure",Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(SqliteActivity.this,"Name或Price不能爲空",Toast.LENGTH_SHORT).show();
                }
            }
        });

        /** * 刪除數據 * * 方式一: db.delete("information", "id =1 ", null); * 方式二: db.delete("information","name = ?", new String[]{"1"}); * 第一個參數:表名 * 第二個參數:where子句 * 第二個參數:where子句 * 返回行數, 0 刪除失敗 * 根據name名刪除數據 * */
        bt_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //
                int information = db.delete("information","name = ?", new String[]{editName.getText().toString()});
                if (information != 0 ){
                    Toast.makeText(SqliteActivity.this,"delete successful", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(SqliteActivity.this,"delete failure", Toast.LENGTH_LONG).show();
                }

            }
        });

        /* * 更新數據 * 根據name修改price * 第一個參數:數據表 * 第二個參數:values * 第三個參數:where子句的內容 * * */
        bt_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                values = new ContentValues();
                values.put("price",editPasswd.getText().toString());
                int information = db.update("information", values, "name = ?", new String[]{editName.getText().toString()});
                if (information != 0 ){
                    Toast.makeText(SqliteActivity.this,"delete successful", Toast.LENGTH_LONG).show();
               }else{
                    Toast.makeText(SqliteActivity.this,"delete failure", Toast.LENGTH_LONG).show();
                }
            }
        });

        /* * 查找數據 * 查找全部數據 * * */
        bt_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                values = new ContentValues();
                //查詢
                Cursor cursor = db.query("information", null, null, null, null, null, null);
              /* * cursor中一些方法的解釋 * 能夠經過列號獲取某一條 數據當中該列上的數據getXXX( * 能夠經過列名獲取列的索引號 getColumnIndex(String columnName) * moveToFirst(),moveToLast(), moveToNext() * 若是moveToFirst返回值爲false,意味着什麼?沒有查詢到數據 * 若是moveToNext返回值爲false,意味着什麼?查詢結果已經遍歷完了, 沒有下一個了 * * */
                //判斷有沒有查詢出來
                if (cursor != null && cursor.moveToFirst()) {

                    //判斷是否已有數據,如有就刪除
                    if (textId != null){
                        Log.i("已清空", "Okk");
                        linearLayoutOut.removeAllViews();
                    }
                    //查詢結果
                    //經過遊標遍歷查詢結果
                    do {
                        //獲取數據
                        int dateId = cursor.getInt(0);
                        String dateName = cursor.getString(cursor.getColumnIndex("name"));
                        int datePrice = cursor.getInt(2);
                        Product product = new Product(dateId,dateName,datePrice);
                        Log.i("獲取的數據",product.toString());
                        linearLayoutIn = new LinearLayout(SqliteActivity.this);
                        textId = new TextView(SqliteActivity.this);
                        textName = new TextView(SqliteActivity.this);
                        textPrice= new TextView(SqliteActivity.this);
                        linearLayoutIn.setOrientation(LinearLayout.HORIZONTAL);
                        //顯示Id
                        textId.setText("Id:"+product.getId()+" ");
                        //顯示name
                        textName.setText("Name:"+product.getName()+" ");
                        //顯示價格
                        textPrice.setText("Price:"+product.getPrice());
                        //將textView添加到linearLayoutIn中
                        linearLayoutIn.addView(textId,layoutParams);
                        linearLayoutIn.addView(textName,layoutParams);
                        linearLayoutIn.addView(textPrice,layoutParams);
                        //將linearLayoutIn添加到LinearLayoutOut中
                        linearLayoutOut.addView(linearLayoutIn);
                    } while (cursor.moveToNext());
                }
            }
        });
    }
}

五、擴展

5.一、getWritableDatabase()和getReadableDatabase()方法區別:

Android使用getWritableDatabase()和getReadableDatabase()方法均可以獲取一個
用於操做數據庫的SQLiteDatabase實例。(getReadableDatabase()方法中會調用getWritableDatabase()方法)
ui

  • getWritableDatabase() 方法以讀寫方式打開數據庫,一旦數據庫的磁盤空間滿了,數據庫就只能讀而不能寫,假若使用的是getWritableDatabase() 方法就會出錯。this

  • getReadableDatabase()方法則是先以讀寫方式打開數據庫,若是數據庫的磁盤空間滿了,就會打開失敗,當打開失敗後會繼續嘗試以只讀方式打開數據庫。若是該問題成功解決,則只讀數據庫對象就會關閉,而後返回一個可讀寫的數據庫對象。spa

5.二、SQLiteDataBase對象各接口說明

  • 一、SQLiteDataBase對象的query()接口:
/** * Query the given table, returning a {@link Cursor} over the result set. * * @param table The table name to compile the query against.(要查詢的表名.) * @param columns A list of which columns to return. Passing null will * return all columns, which is discouraged to prevent reading * data from storage that isn't going to be used.(想要顯示的列,若爲空則返回全部列,不建議設置爲空,若是不是返回全部列) * @param selection A filter declaring which rows to return, formatted as an * SQL WHERE clause (excluding the WHERE itself). Passing null * will return all rows for the given table. * (where子句,聲明要返回的行的要求,若是爲空則返回表的全部行。) * @param selectionArgs You may include ?s in selection, which will be * replaced by the values from selectionArgs, in order that they * appear in the selection. The values will be bound as Strings. * ( where子句對應的條件值) * @param groupBy A filter declaring how to group rows, formatted as an SQL * GROUP BY clause (excluding the GROUP BY itself). Passing null * will cause the rows to not be grouped. * (分組方式,若爲空則不分組.) * @param having A filter declare which row groups to include in the cursor, * if row grouping is being used, formatted as an SQL HAVING * clause (excluding the HAVING itself). Passing null will cause * all row groups to be included, and is required when row * grouping is not being used. * (having條件,若爲空則返回所有(不建議)) * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause * (excluding the ORDER BY itself). Passing null will use the * default sort order, which may be unordered. * (排序方式,爲空則爲默認排序方式) * @return A {@link Cursor} object, which is positioned before the first entry. Note that * {@link Cursor}s are not synchronized, see the documentation for more details. * @see Cursor */
    public Cursor query(String table, String[] columns, String selection,
            String[] selectionArgs, String groupBy, String having,
            String orderBy) {

        return query(false, table, columns, selection, selectionArgs, groupBy,
                having, orderBy, null /* limit */);
    }
  • 二、SQLiteDataBase對象的insert()接口:
/** * Convenience method for inserting a row into the database. * * @param table the table to insert the row into(表名) * @param nullColumnHack optional; may be <code>null</code>. * SQL doesn't allow inserting a completely empty row without * naming at least one column name. If your provided <code>values</code> is * empty, no column names are known and an empty row can't be inserted. * If not set to null, the <code>nullColumnHack</code> parameter * provides the name of nullable column name to explicitly insert a NULL into * in the case where your <code>values</code> is empty. * ( 當values參數爲空或者裏面沒有內容的時候,咱們insert是會失敗的(底層數據庫不容許插入一個空行),爲了防止這種狀況,咱們要在這裏指定一個 列名,到時候若是發現將要插入的行爲空行時,就會將你指定的這個列名的值設爲null,而後再向數據庫中插入。) * @param values this map contains the initial column values for the * row. The keys should be the column names and the values the * column values * (一個ContentValues對象,相似一個map.經過鍵值對的形式存儲值。) * @return the row ID of the newly inserted row, or -1 if an error occurred */
    public long insert(String table, String nullColumnHack, ContentValues values) {
        try {
            return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
        } catch (SQLException e) {
            Log.e(TAG, "Error inserting " + values, e);
            return -1;
        }
    }
  • 三、SQLiteDataBase對象的update()接口:
/** * Convenience method for updating rows in the database. * * @param table the table to update in(要更新的表名) * @param values a map from column names to new column values. null is a * valid value that will be translated to NULL. * * @param whereClause the optional WHERE clause to apply when updating. * Passing null will update all rows. * (可選的where語句) * @param whereArgs You may include ?s in the where clause, which * will be replaced by the values from whereArgs. The values * will be bound as Strings. * (whereClause語句中表達式的?佔位參數列表) * @return the number of rows affected */
    public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
        return updateWithOnConflict(table, values, whereClause, whereArgs, CONFLICT_NONE);
    }
  • 四、SQLiteDataBase對象的delete()接口:
/** * Convenience method for deleting rows in the database. * * @param table the table to delete from(表名) * @param whereClause the optional WHERE clause to apply when deleting. * Passing null will delete all rows. * (可選的where語句) * @param whereArgs You may include ?s in the where clause, which * will be replaced by the values from whereArgs. The values * will be bound as Strings. * (whereClause語句中表達式的?佔位參數列表) * @return the number of rows affected if a whereClause is passed in, 0 * otherwise. To remove all rows and get a count pass "1" as the * whereClause. */
    public int delete(String table, String whereClause, String[] whereArgs) {
        acquireReference();
        try {
            SQLiteStatement statement =  new SQLiteStatement(this, "DELETE FROM " + table +
                    (!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs);
            try {
                return statement.executeUpdateDelete();
            } finally {
                statement.close();
            }
        } finally {
            releaseReference();
        }
    }
相關文章
相關標籤/搜索