主要就是对SQL语句操作数据库和SQLite数据库中的事务
之前我用的第三方模拟器 然后自带删掉了一些东西 如果HAXM无法安装:
去文件里找到安装
参考 https://blog.csdn.net/m0_63131732/article/details/125736265
之前一直好奇为啥不能写成switch case语句:就是R.id找不到
就是存储的资源ID不是常量
参考 https://blog.csdn.net/jieranjie/article/details/129496207
SQL语句查询和事务
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) { } }
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(); } }
假如 不开启事务中间出现一条错误查询:
则如图:高远减少了 芳芳的钱不增加 出现错误
开启事务后出现错误 则回滚 两者的钱都不变 所以数据库的事务很重要
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?