Android数据存储之Sqlite数据库存储

Android数据存储之Sqlite数据库存储

1.继承SQLiteOpenHelper

创建一个用于管理数据库创建和版本管理的助手类。

package com.androidlearning.datastore_88;

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

import androidx.annotation.Nullable;

/**
 * 实现数据库帮助抽象类
 * @author 刘昌兴
 * @date 2022/3/11 15:02
 */
public class SQLiteHelper extends SQLiteOpenHelper {
    public SQLiteHelper(@Nullable Context context,int version) {
        super(context, "school.db", null, version);
    }
    /**
     * 1.数据库文件创建时调用(1次)
     * 2.在此方法中进行建表和初始化数据
     * @author 刘昌兴
     * @date 2022/3/11 15:13
     * @param db
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.i("TAG","SQLiteHelper onCreate");
        //创建数据库
        String sql="create table student(_id integer primary key autoincrement,name varchar,age Integer,grade varchar)";
        db.execSQL(sql);
        //初始化数据
        db.execSQL("insert into student(name,age,grade) values('周华健',18,'三年一班')");
        db.execSQL("insert into student(name,age,grade) values('黄建国',20,'三年一班')");
        db.execSQL("insert into student(name,age,grade) values('王维',25,'三年二班')");
        db.execSQL("insert into student(name,age,grade) values('何淑华',23,'三年三班')");
    }
    /**
     * 更新数据库
     * @author 刘昌兴
     * @date 2022/3/11 15:39
     * @param db
     * @param oldVersion
     * @param newVersion
     * @return
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.i("TAG","SQLiteHelper onUpgrade");
    }
}

2.获得连接后实现增删改查及事物

具体见代码

package com.androidlearning.datastore_88;

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.Toast;

public class DatabaseStore extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_database_store);
    }
    /*
     * 创建库
     */
    public void testCreateDB(View v) {
        //创建SQLiteHelper对象
        SQLiteHelper sqLiteHelper=new SQLiteHelper(this,1);
        //获得连接
        SQLiteDatabase sqLiteDatabase=sqLiteHelper.getWritableDatabase();
        Toast.makeText(this,"创建数据库成功",Toast.LENGTH_SHORT).show();
    }

    /*
     * 更新库
     */
    public void testUpdateDB(View v) {
        //创建SQLiteHelper对象
        SQLiteHelper sqLiteHelper=new SQLiteHelper(this,2);
        //获得连接
        SQLiteDatabase sqLiteDatabase=sqLiteHelper.getWritableDatabase();
        Toast.makeText(this,"更新数据库成功",Toast.LENGTH_SHORT).show();
    }

    /*
     * 添加记录
     */
    public void testInsert(View v) {
        //创建SQLiteHelper对象
        SQLiteHelper sqLiteHelper=new SQLiteHelper(this,2);
        //获得连接
        SQLiteDatabase sqLiteDatabase=sqLiteHelper.getWritableDatabase();
        //插入数据
        //创建字段-数值对象
        ContentValues contentValues=new ContentValues();
        contentValues.put("name","王宇飞");
        contentValues.put("age",29);
        contentValues.put("grade","三年一班");
        long id = sqLiteDatabase.insert("student", null, contentValues);
        //关闭连接
        sqLiteDatabase.close();
        //提示
        Toast.makeText(this,"学生id:"+id,Toast.LENGTH_SHORT).show();
    }

    /*
     * 更新
     */
    public void testUpdate(View v) {
        //创建SQLiteHelper对象
        SQLiteHelper sqLiteHelper=new SQLiteHelper(this,2);
        //获得连接
        SQLiteDatabase sqLiteDatabase=sqLiteHelper.getWritableDatabase();
        //更新数据
        ContentValues contentValues=new ContentValues();
        contentValues.put("age",30);
        contentValues.put("grade","三年二班");
        int updateRow = sqLiteDatabase.update("student", contentValues, "_id=?", new String[]{"5"});
        //关闭连接
        sqLiteDatabase.close();
        //提示
        Toast.makeText(this,"更新"+updateRow+"行数据",Toast.LENGTH_SHORT).show();
    }

    /*
     * 删除
     */
    public void testDelete(View v) {
        //创建SQLiteHelper对象
        SQLiteHelper sqLiteHelper=new SQLiteHelper(this,2);
        //获得连接
        SQLiteDatabase sqLiteDatabase=sqLiteHelper.getWritableDatabase();
        //删除数据
        int deleteRow = sqLiteDatabase.delete("student", "_id=2",null);
        //关闭连接
        sqLiteDatabase.close();
        //提示
        Toast.makeText(this,"删除"+deleteRow+"行数据",Toast.LENGTH_SHORT).show();
    }

    /*
     * 查询
     */
    public void testQuery(View v) {
        //创建SQLiteHelper对象
        SQLiteHelper sqLiteHelper=new SQLiteHelper(this,2);
        //获得连接
        SQLiteDatabase sqLiteDatabase=sqLiteHelper.getWritableDatabase();
        //查询
//        Cursor studentCursor = sqLiteDatabase.query("student", null, null, null, null, null, null);
        //条件查询
        Cursor studentCursor = sqLiteDatabase.query("student", null, "_id=?", new String[]{"3"}, null, null, null);
        int sum=studentCursor.getCount();
        Toast.makeText(this,"共有"+sum+"条数据",Toast.LENGTH_SHORT).show();
        while(studentCursor.moveToNext()){
            int id=studentCursor.getInt(0);
            String name=studentCursor.getString(1);
            int age=studentCursor.getInt(2);
            String grade=studentCursor.getString(studentCursor.getColumnIndex("grade"));
            Log.i("students",id+"-"+name+"-"+age+"-"+grade);
        }
        //关闭游标
        studentCursor.close();
        //关闭连接
        sqLiteDatabase.close();
    }


    /*
     * 测试事务处理
     */
    public void testTransaction(View v) {
        //创建SQLiteHelper对象
        SQLiteHelper sqLiteHelper=new SQLiteHelper(this,2);
        //获得连接
        SQLiteDatabase sqLiteDatabase=sqLiteHelper.getWritableDatabase();
        try{
            //开启事务
            sqLiteDatabase.beginTransaction();
            //更新第一条数据
            ContentValues contentValues=new ContentValues();
            contentValues.put("age",25);
            int updateRow1 = sqLiteDatabase.update("student", contentValues, "_id=?", new String[]{"4"});
            Log.i("transaction","updateRow1:"+updateRow1);
            if(true)
                throw new RuntimeException("出异常了!!!");
            //更新第二条数据
            contentValues=new ContentValues();
            contentValues.put("age",25);
            int updateRow2 = sqLiteDatabase.update("student", contentValues, "_id=?", new String[]{"5"});
            Log.i("transaction","updateRow2:"+updateRow2);
            //完成提交事物
            sqLiteDatabase.setTransactionSuccessful();
        }finally {
            //结束事物
            sqLiteDatabase.endTransaction();
            //关闭连接
            sqLiteDatabase.close();
        }
    }

}

你可能感兴趣的:(Android,android,sqlite3)