4.3

所花时间(包括上课):2.5

打码量(行):360

博客量(篇):1

了解到知识点:学习数据删除

 

 import android.content.ContentValues;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.os.Bundle;

import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

 

public class MainActivity extends AppCompatActivity {

 

    private static final String TAG = "MainActivity";

    private NotesDbHelper dbHelper;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        dbHelper = new NotesDbHelper(this);

 

        // 示例:删除 id 为 1 的数据行

        deleteNoteById(1);

    }

 

    private void deleteNoteById(long id) {

        // 获取可写的数据库实例

        SQLiteDatabase db = dbHelper.getWritableDatabase();

 

        // 定义删除条件

        String selection = NotesContract.NoteEntry._ID + " = ?";

        String[] selectionArgs = { String.valueOf(id) };

 

        // 执行删除操作

        int deletedRows = db.delete(NotesContract.NoteEntry.TABLE_NAME, selection, selectionArgs);

 

        Log.d(TAG, "Deleted rows: " + deletedRows);

 

        // 关闭数据库连接

        db.close();

    }

}

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

 

public class NotesDbHelper extends SQLiteOpenHelper {

 

    public static final int DATABASE_VERSION = 1;

    public static final String DATABASE_NAME = "Notes.db";

 

    private static final String SQL_CREATE_ENTRIES =

            "CREATE TABLE " + NotesContract.NoteEntry.TABLE_NAME + " (" +

                    NotesContract.NoteEntry._ID + " INTEGER PRIMARY KEY," +

                    NotesContract.NoteEntry.COLUMN_NAME_CONTENT + " TEXT)";

 

    private static final String SQL_DELETE_ENTRIES =

            "DROP TABLE IF EXISTS " + NotesContract.NoteEntry.TABLE_NAME;

 

    public NotesDbHelper(Context context) {

        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }

 

    @Override

    public void onCreate(SQLiteDatabase db) {

        db.execSQL(SQL_CREATE_ENTRIES);

    }

 

    @Override

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

        db.execSQL(SQL_DELETE_ENTRIES);

        onCreate(db);

    }

}

import android.provider.BaseColumns;

 

public final class NotesContract {

 

    private NotesContract() {}

 

    public static class NoteEntry implements BaseColumns {

        public static final String TABLE_NAME = "notes";

        public static final String COLUMN_NAME_CONTENT = "content";

    }

}

posted @ 2024-04-03 21:53  赵千万  阅读(4)  评论(0编辑  收藏  举报