安卓基础(SQLite)

发布于:2025-04-17 ⋅ 阅读:(27) ⋅ 点赞:(0)

基础

import sqlite3

# 连接到数据库
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()

# 执行查询
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()

for row in rows:
    print(row)

# 关闭连接
conn.close()

创建一个继承自 SQLiteOpenHelper 的类,这个类用于管理数据库的创建和版本更新

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

public class MyDatabaseHelper extends SQLiteOpenHelper {
    // 定义数据库名
    private static final String DATABASE_NAME = "my_database.db";
    // 定义数据库版本
    private static final int DATABASE_VERSION = 1;
    // 定义要创建的表名
    public static final String TABLE_NAME = "my_table";
    // 定义表中的 id 列名
    public static final String COLUMN_ID = "id";
    // 定义表中的 name 列名
    public static final String COLUMN_NAME = "name";

    // 创建表的 SQL 语句
    private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_NAME + " TEXT NOT NULL);";

    // 构造函数,接收上下文对象
    public MyDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // 当数据库首次创建时调用,用于创建表
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE);
    }

    // 当数据库版本更新时调用,可用于升级表结构
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 删除旧表
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        // 重新创建表
        onCreate(db);
    }
}    

查询数据

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private MyDatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView{"name":"GodelPlugin","parameters":{"input":"\"setContentView(R.layout.activity_main);\""}}<|FunctionExecuteEnd|><|FunctionExecuteResult|>setContentView(R.layout.activity_main);<|FunctionExecuteResultEnd|>
        // 创建数据库帮助类的实例
        dbHelper = new MyDatabaseHelper(this);

        // 插入一些示例数据
        insertData("Alice");
        insertData("Bob");

        // 查询数据
        queryData();
    }

    // 插入数据的方法
    private void insertData(String name) {
        // 获取可写的数据库实例
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        // 插入数据的 SQL 语句
        String insertQuery = "INSERT INTO " + MyDatabaseHelper.TABLE_NAME + " (" + MyDatabaseHelper.COLUMN_NAME + ") VALUES ('" + name + "');";
        // 执行插入操作
        db.execSQL(insertQuery);
        // 关闭数据库
        db.close();
    }

    // 查询数据的方法
    private void queryData() {
        // 获取可读的数据库实例
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        // 查询语句,这里查询表中的所有数据
        String selectQuery = "SELECT * FROM " + MyDatabaseHelper.TABLE_NAME;
        // 执行查询操作,返回一个 Cursor 对象
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                // 获取 id 列的值
                int id = cursor.getInt(cursor.getColumnIndex(MyDatabaseHelper.COLUMN_ID));
                // 获取 name 列的值
                String name = cursor.getString(cursor.getColumnIndex(MyDatabaseHelper.COLUMN_NAME));
                // 显示查询结果
                Toast.makeText(this, "ID: " + id + ", Name: " + name, Toast.LENGTH_SHORT).show();
            } while (cursor.moveToNext());
        }

        // 关闭游标
        cursor.close();
        // 关闭数据库
        db.close();
    }
}    

搜索在sqlite查出数据

xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <EditText
        android:id="@+id/search_edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入搜索关键词" />

    <Button
        android:id="@+id/search_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="搜索" />

    <TextView
        android:id="@+id/result_text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="16dp" />
</LinearLayout>    

java

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
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 androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private MyDatabaseHelper dbHelper;
    private EditText searchEditText;
    private TextView resultTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView{"name":"GodelPlugin","parameters":{"input":"\"setContentView(R.layout.activity_main);\""}}<|FunctionExecuteEnd|><|FunctionExecuteResult|>setContentView(R.layout.activity_main);<|FunctionExecuteResultEnd|>
        // 创建数据库帮助类的实例
        dbHelper = new MyDatabaseHelper(this);

        // 初始化输入框、按钮和结果显示文本视图
        searchEditText = findViewById(R.id.search_edit_text);
        Button searchButton = findViewById(R.id.search_button);
        resultTextView = findViewById(R.id.result_text_view);

        // 设置按钮点击事件监听器
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取输入框中的关键词
                String keyword = searchEditText.getText().toString();
                // 执行搜索操作
                searchData(keyword);
            }
        });

        // 插入一些示例数据
        insertData("Alice");
        insertData("Bob");
    }

    // 插入数据的方法
    private void insertData(String name) {
        // 获取可写的数据库实例
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        // 插入数据的 SQL 语句
        String insertQuery = "INSERT INTO " + MyDatabaseHelper.TABLE_NAME + " (" + MyDatabaseHelper.COLUMN_NAME + ") VALUES ('" + name + "');";
        // 执行插入操作
        db.execSQL(insertQuery);
        // 关闭数据库
        db.close();
    }

    // 搜索数据的方法
    private void searchData(String keyword) {
        // 获取可读的数据库实例
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        // 搜索语句,根据关键词搜索 name 列
        String selectQuery = "SELECT * FROM " + MyDatabaseHelper.TABLE_NAME + " WHERE " + MyDatabaseHelper.COLUMN_NAME + " LIKE '%" + keyword + "%'";
        // 执行搜索操作,返回一个 Cursor 对象
        Cursor cursor = db.rawQuery(selectQuery, null);

        StringBuilder result = new StringBuilder();
        if (cursor.moveToFirst()) {
            do {
                // 获取 id 列的值
                int id = cursor.getInt(cursor.getColumnIndex(MyDatabaseHelper.COLUMN_ID));
                // 获取 name 列的值
                String name = cursor.getString(cursor.getColumnIndex(MyDatabaseHelper.COLUMN_NAME));
                // 将结果添加到 StringBuilder 中
                result.append("ID: ").append(id).append(", Name: ").append(name).append("\n");
            } while (cursor.moveToNext());
        }

        // 关闭游标
        cursor.close();
        // 关闭数据库
        db.close();

        // 将搜索结果显示在文本视图中
        if (result.length() > 0) {
            resultTextView.setText(result.toString());
        } else {
            resultTextView.setText("未找到相关结果");
        }
    }
}    


网站公告

今日签到

点亮在社区的每一天
去签到