当前位置: 首页 > article >正文

7-1.Android SQLite 之 SQLiteDatabase 简单编码模板(SQLiteDatabase 使用、SQL 语句编写)

一、SQLiteDatabase

  1. SQLite 是一种轻量级的数据库引擎,它非常适合在移动设备(例如,Android)上使用

  2. SQLiteDatabase 允许应用程序与 SQLite 数据库进行交互,它提供了增删改查等一系列方法


二、SQLiteDatabase 简单编码

1、Application
  • MyApplication.javas
package com.my.database.application;

import android.app.Application;
import android.content.Context;

public class MyApplication extends Application {

    public static final String TAG = MyApplication.class.getSimpleName();

    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();

        context = this;
    }

    public static Context getContext() {
        return context;
    }
}
2、Note
  • Note.java
package com.my.database.entity;

public class Note {
    private int id;
    private String title;
    private String content;

    public Note(int id, String title, String content) {
        this.id = id;
        this.title = title;
        this.content = content;
    }

    public int getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "Note{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                '}';
    }
}
3、Database
  • MyDatabaseManager.java
package com.my.database.mydatabase;

import android.annotation.SuppressLint;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.my.database.application.MyApplication;
import com.my.database.entity.Note;

import java.util.ArrayList;
import java.util.List;

public class MyDatabaseManager {

    public static final String TAG = MyDatabaseManager.class.getSimpleName();

    private SQLiteDatabase sqLiteDatabase;

    private static MyDatabaseManager myDatabaseManager;

    private static final String DATABASE_NAME = "test.db";

    private static final String TABLE_NAME = "Note";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_TITLE = "title";
    private static final String COLUMN_CONTENT = "content";


    private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " ("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + COLUMN_TITLE + " TEXT, "
            + COLUMN_CONTENT + " TEXT);";

    private MyDatabaseManager() {
        sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(MyApplication.getContext().getDatabasePath(DATABASE_NAME).toString(), null);
        sqLiteDatabase.execSQL(CREATE_TABLE);
    }

    public static MyDatabaseManager getInstance() {
        if (myDatabaseManager == null) myDatabaseManager = new MyDatabaseManager();
        return myDatabaseManager;
    }

    public void insert(Note note) {
        sqLiteDatabase.execSQL("INSERT INTO " + TABLE_NAME + " (" + COLUMN_TITLE + ", " + COLUMN_CONTENT + ") VALUES (?, ?);",
                new Object[]{note.getTitle(), note.getContent()});
    }

    public void delete(int id) {
        sqLiteDatabase.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " + COLUMN_ID + " = ?;", new Object[]{id});
    }

    public void update(Note note) {
        sqLiteDatabase.execSQL("UPDATE " + TABLE_NAME + " SET " + COLUMN_TITLE + " = ?, " + COLUMN_CONTENT + " = ? WHERE " + COLUMN_ID + " = ?;",
                new Object[]{note.getTitle(), note.getContent(), note.getId()});
    }

    @SuppressLint("Range")
    public List<Note> queryAll() {
        Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + TABLE_NAME + ";", null);

        if (cursor.moveToFirst()) {
            List<Note> notes = new ArrayList<>();

            do {
                Note note = new Note(
                        cursor.getInt(cursor.getColumnIndex(COLUMN_ID)),
                        cursor.getString(cursor.getColumnIndex(COLUMN_TITLE)),
                        cursor.getString(cursor.getColumnIndex(COLUMN_CONTENT))
                );

                notes.add(note);
            } while (cursor.moveToNext());

            return notes;
        }

        return null;
    }
}
4、Activity Layout
  • activity_note.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".NoteActivity">

    <Button
        android:id="@+id/btn_insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_insert" />

    <Button
        android:id="@+id/btn_update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_delete" />

    <Button
        android:id="@+id/btn_query_all"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_update" />
</androidx.constraintlayout.widget.ConstraintLayout>
5、Activity Code
  • NoteActivity.java
package com.my.database;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.Button;

import com.my.database.entity.Note;
import com.my.database.mydatabase.MyDatabaseManager;

import java.util.List;

public class NoteActivity extends AppCompatActivity {

    public static final String TAG = NoteActivity.class.getSimpleName();

    private MyDatabaseManager myDatabaseManager;

    private Button btnInsert;
    private Button btnDelete;
    private Button btnUpdate;
    private Button btnQueryAll;

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

        myDatabaseManager = MyDatabaseManager.getInstance();

        btnInsert = findViewById(R.id.btn_insert);
        btnDelete = findViewById(R.id.btn_delete);
        btnUpdate = findViewById(R.id.btn_update);
        btnQueryAll = findViewById(R.id.btn_query_all);

        btnInsert.setOnClickListener(v -> {
            Note note1 = new Note(0, "A", "AAA");
            Note note2 = new Note(0, "B", "BBB");
            myDatabaseManager.insert(note1);
            myDatabaseManager.insert(note2);
            Log.i(TAG, "------------------------------ insert ok");
        });

        btnDelete.setOnClickListener(v -> {
            myDatabaseManager.delete(1);
            myDatabaseManager.delete(2);
            Log.i(TAG, "------------------------------ delete ok");
        });

        btnUpdate.setOnClickListener(v -> {
            Note note1 = new Note(0, "A+", "AAA+");
            Note note2 = new Note(0, "B+", "BBB+");
            myDatabaseManager.update(note1);
            myDatabaseManager.update(note2);
            Log.i(TAG, "------------------------------ update ok");
        });

        btnQueryAll.setOnClickListener(v -> {
            List<Note> notes = myDatabaseManager.queryAll();
            if (notes == null) {
                Log.i(TAG, "------------------------------ queryAll - notes is null");
                return;
            }
            if (notes.size() == 0) {
                Log.i(TAG, "------------------------------ queryAll - notes is empty");
                return;
            }

            for (Note note : notes) Log.i(TAG, "------------------------------ queryAll - " + note);
        });
    }
}
Test
  • 增 -> 改 -> 查 -> 删 -> 查,输出结果
I/NoteActivity: ------------------------------ insert ok
I/NoteActivity: ------------------------------ update ok
I/NoteActivity: ------------------------------ queryAll - Note{id=1, title='A', content='AAA'}
I/NoteActivity: ------------------------------ queryAll - Note{id=2, title='B', content='BBB'}
I/NoteActivity: ------------------------------ delete ok
I/NoteActivity: ------------------------------ queryAll - notes is null

三、SQLiteDatabase 简单编码案例解析

1、数据库结构
  1. 数据库文件名为 test.db
private static final String DATABASE_NAME = "test.db";
  1. 数据库中有 Note 表,它包含三个字段
private static final String TABLE_NAME = "Note";

private static final String COLUMN_ID = "id";
private static final String COLUMN_TITLE = "title";
private static final String COLUMN_CONTENT = "content";
字段类型备注
id整型主键,自增
title文本-
content文本-
2、单例模式
  1. MyDatabaseManager 的构造函数是私有的,防止外部代码直接创建实例对象
private MyDatabaseManager() {
    ...
}
  1. MyDatabaseManager 实例对象只能通过 getInstance 方法获取,该方法确保了整个应用程序中只有一个 MyDatabaseManager 实例对象
public static MyDatabaseManager getInstance() {
    if (myDatabaseManager == null) myDatabaseManager = new MyDatabaseManager();
    return myDatabaseManager;
}
3、数据库创建
  1. SQLiteDatabase.openOrCreateDatabase 方法用于打开或创建一个数据库,如果数据库存在,就是打开,如果数据库不存在,就是创建
sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(MyApplication.getContext().getDatabasePath(DATABASE_NAME).toString(), null);
  1. execSQL 方法用于执行 SQL 语句
sqLiteDatabase.execSQL(CREATE_TABLE);
4、数据库操作
(1)增 insert
  • 接收一个 Note 对象并将其插入数据库
public void insert(Note note) {
    sqLiteDatabase.execSQL("INSERT INTO " + TABLE_NAME + " (" + COLUMN_TITLE + ", " + COLUMN_CONTENT + ") VALUES (?, ?);",
            new Object[]{note.getTitle(), note.getContent()});
}
(2)删 delete
  • 接收一个 id 来删除对应的记录
public void delete(int id) {
    sqLiteDatabase.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " + COLUMN_ID + " = ?;", new Object[]{id});
}
(3)改 update
  • 接收一个 Note 对象并根据 id 更新对应的记录
public void update(Note note) {
    sqLiteDatabase.execSQL("UPDATE " + TABLE_NAME + " SET " + COLUMN_TITLE + " = ?, " + COLUMN_CONTENT + " = ? WHERE " + COLUMN_ID + " = ?;",
            new Object[]{note.getTitle(), note.getContent(), note.getId()});
}
(4)查 queryAll
  • 查询返回所有的行
@SuppressLint("Range")
public List<Note> queryAll() {
    Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + TABLE_NAME + ";", null);

    if (cursor.moveToFirst()) {
        List<Note> notes = new ArrayList<>();

        do {
            Note note = new Note(
                    cursor.getInt(cursor.getColumnIndex(COLUMN_ID)),
                    cursor.getString(cursor.getColumnIndex(COLUMN_TITLE)),
                    cursor.getString(cursor.getColumnIndex(COLUMN_CONTENT))
            );

            notes.add(note);
        } while (cursor.moveToNext());

        cursor.close();
        return notes;
    }

    cursor.close();
    return null;
}

四、SQLiteDatabase 简单编码 SQL 语句

1、数据创建
CREATE TABLE IF NOT EXISTS Note (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT,
    content TEXT
);
// 写成一行

CREATE TABLE IF NOT EXISTS Note (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, content TEXT);
2、数据库操作
(1)增 insert
INSERT INTO Note (
    title,
    content
) VALUES (
    【title】,
    【content】
);
// 写成一行

INSERT INTO Note (title, content) VALUES (【title】, 【content】);
(2)删 delete
// 写成一行

DELETE FROM Note WHERE id = 【id】;
(3)改 update
UPDATE Note SET
    title = 【title】,
    content = 【content】
WHERE id = 【id】;
// 写成一行

UPDATE Note SET title = 【title】, content = 【content】 WHERE id = 【id】;
(4)查 queryAll
// 写成一行

SELECT * FROM Note;
注意事项
  1. SQL 语句最好先在其他编辑器中写好,如果直接在代码中编写,极易写错

  2. SQL 语句屑好后,最好改写成一行,之后粘贴到代码中,然后调整结构,否则结构会混乱

// 这是没写成一行的 SQL 语句

private static final  String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS Note (\n" +
        "    id INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
        "    title TEXT,\n" +
        "    content TEXT\n" +
        ");";
// 这写成一行的 SQL 语句(粘贴到代码中,然后调整结构的)

private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS Note (" +
        "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
        "title TEXT, " +
        "content TEXT);";

http://www.kler.cn/news/327887.html

相关文章:

  • 矩阵系统源码搭建的具体步骤,支持oem,源码搭建
  • Redis的基础通用命令
  • 3D Gaussian Splatting 学习笔记
  • VTK 与 OpenCV 的区别和各自的特点
  • 【笔记】X射线的衍射方向
  • golang学习笔记26-管道(Channel)【重要】
  • mock数据,不使用springboot的单元测试
  • 5G N2 N3 N6 NB口
  • C语言系列4——指针与数组(1)
  • 以矩阵的视角解多元一次方程组——矩阵消元
  • 需求6:如何写一个后端接口?
  • 使用JavaScript实现动态表格
  • 【MYSQL】授权远程连接的用户
  • Web认识 -- 第一课
  • 使用AT command 修改手机APN
  • Python Pandas轻松实现函数式编程
  • springboot+neo4j demo
  • jQuery UI 工作原理
  • 基于微信小程序的旅游助手的设计与实现(源码+定制+文档讲解)
  • Android常用C++特性之std::make_unique
  • 【机器学习基础】Transformer学习
  • CATIA风扇
  • 数据可视化分析系统-解锁企业信息的利器
  • 小徐影院:Spring Boot技术下的影院革新
  • SOMEIP_ETS_143: SD_Request_non_existing_ServiceID
  • 完整网络模型训练(一)
  • c语言实例
  • GWAS分析中显著位点如何注释基因:excel???
  • Ubuntu22.04安装VMware Tools
  • Autosar CP系列:传感器/执行器设计模式