主要就是对SQL语句操作数据库和SQLite数据库中的事务

之前我用的第三方模拟器 然后自带删掉了一些东西 如果HAXM无法安装:
去文件里找到安装
参考 https://blog.csdn.net/m0_63131732/article/details/125736265

image
之前一直好奇为啥不能写成switch case语句:就是R.id找不到
就是存储的资源ID不是常量
参考 https://blog.csdn.net/jieranjie/article/details/129496207


SQL语句查询和事务

image

package com.example.store;

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

import androidx.annotation.Nullable;

public class Myhelper extends SQLiteOpenHelper {

    public Myhelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table fang1(name varchar(20),account int)");
    }

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

image

package com.example.store;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class UseMyhelper extends AppCompatActivity {
    Myhelper myhelper;
    SQLiteDatabase db;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
    }

    private void initData() {
        //插入数据操作
        myhelper = new Myhelper(UseMyhelper.this, "fang.db", null, 1);
        db = myhelper.getWritableDatabase();

        ContentValues contentValues1 = new ContentValues();
        contentValues1.put("name", "高远");
        contentValues1.put("account", 2000);
        db.insert("fang1", null, contentValues1);

        //使用SQL方式进行操作
        db.execSQL("insert into fang1(name,account) values(?,?)",new Object[]{"芳芳",3000});

        db.close();
    }

    private void Transaction() {
        myhelper = new Myhelper(UseMyhelper.this, "fang.db", null, 1);
        db = myhelper.getWritableDatabase();
        //开启数据库事务
        db.beginTransaction();
        //加钱 少钱
        db.execSQL("update fang1 set account=account-1000 where name=?", new Object[]{"高远"});
        //假设进行一个错误的查询 不开启事务 则上条语句高远的account减少而芳芳的account不会增加执行
        //体现事务的原子性
//        db.execSQL("select*from fangfang");


        db.execSQL("update fang1 set account=account+1000 where name=?", new Object[]{"芳芳"});
        //标记数据库事务执行成功
        db.setTransactionSuccessful();
        //关闭事务
        db.endTransaction();
        //关闭比数据库
        db.close();
    }

}

假如 不开启事务中间出现一条错误查询:
则如图:高远减少了 芳芳的钱不增加 出现错误

image

开启事务后出现错误 则回滚 两者的钱都不变 所以数据库的事务很重要

posted on 2024-05-13 09:37  蒸饺  阅读(12)  评论(0)    收藏  举报