安卓实战开发之SQLite从简单使用crud

2024-09-03 02:18

本文主要是介绍安卓实战开发之SQLite从简单使用crud,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言

最近项目忙,然后呢很久没有更新博客了,react-native也是没有时间学习,然后项目里面用到了数据持久化(数据存储),Android系统中主要提供了三种数据持久化方式:文件存储、SharedPreference存储、数据库存储。说实在的毕竟app这种轻量级的使用数据库还是不多,然后呢要使用数据库也是在特定场合,这也导致了很多的移动端开发(对数据库操作不多)对数据库使用不太熟练。

应用场景

一般我们都不使用数据库的,基本上使用SharedPreference就能处理大部分问题,然后在特定场合比如做商城类资讯类及三级缓存图片地址时候就可能需要使用数据库,真到用的时候就要google和baidu了,对于数据简单并且不需要频繁操作数据的我们就参考下别人demo好了,然后数据存储量大比如新闻、缓存的离线天气、商品列表等我们就不得不去考虑性能了,然后开发就要考虑时间和性能你可能会使用greenDao、LitePal、realm。

效果如下:

这里写图片描述

简单使用SQLite用例

1.创建SQLite数据库:
public MyDatabaseHelper(Context context, String name, CursorFactory factory, int version) {super(context, name, factory, version);}public void onCreate(SQLiteDatabase db) {db.execSQL(CREATE_BOOK);}public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
2.升级SQLite数据库
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {db.execSQL("drop table if exists ***");db.execSQL("drop table if exists ***");onCreate(db);}
3.在活动中创建SQLiteOpenHelper实现类的实例,调用其getWritableDatabase()方法;
MyDatabaseHelper dbHelper = new MyDatabaseHelper(this, "**.db", null, 1);
dbHelper.getWritableDatabase();
4.CRUD操作

CRUD我们可以通过像java使用hibernate样既可以执行原生的sql语句(db.execSQL(**))也可以执行自带的封装语句ad.insert。

  • insert()
    添加(Create):先将数据添加至ContentValues对象,然后调用insert()方法。
ContentValues values = new ContentValues();values.put("key1", value1);values.put("key2", value2);values.put("key3", value3);db.insert("table", null, values);values.clear();
  • query()
    查询(Retrieve):query()方法用于对数据进行查询,但即使是其最短的重载方法也有7个参数,其定义为:
Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
  • update()
    更新(Update):update()方法用于对数据进行更新,接收4个参数:
public int update (String table, ContentValues values, String whereClause, String[] whereArgs)
  • delete()
    删除(Delete):delete()方法用于删除数据,接收3个参数:
public int delete (String table, String whereClause, String[] whereArgs)

Sqlite项目简单使用详解

创建数据库:

package com.losileeya.dbsimple.db;import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;public class MyHelper extends SQLiteOpenHelper {private static String DB_NAME = "mydata.db";  //数据库名称public static String TABLE_NAME = "employee"; //表名/**super(参数1,参数2,参数3,参数4),其中参数4是代表数据库的版本,* 是一个大于等于1的整数,如果要修改(添加字段)表中的字段,则设置* 一个比当前的 参数4大的整数 ,把更新的语句写在onUpgrade(),下一次* 调用*/public MyHelper(Context context) {super(context, DB_NAME, null, 2);}@Overridepublic void onCreate(SQLiteDatabase db) {//Create tableString sql = "CREATE TABLE "+TABLE_NAME + "("+ "_id INTEGER PRIMARY KEY,"+ "name TEXT," + "sex TEXT);";Log.e("table oncreate", "create table");db.execSQL(sql);        //创建表}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stubLog.e("update", "update");
//      db.execSQL("ALTER TABLE "+ MyHelper.TABLE_NAME+" ADD sex TEXT"); //修改字段String sql = "DROP TABLE IF EXISTS " + TABLE_NAME;db.execSQL(sql);this.onCreate(db);}}

实际数据操作,进行crud

package com.losileeya.dbsimple.db;import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;import com.losileeya.dbsimple.bean.Person;import java.util.ArrayList;
import java.util.List;public class DatabaseUtil {private MyHelper helper;private SQLiteDatabase db;public DatabaseUtil(Context context) {super();helper = new MyHelper(context);db = helper.getWritableDatabase();}/*** 插入数据* * param String* */public boolean Insert(Person person) {// String sql = "insert into " + MyHelper.TABLE_NAME// + "(name,sex) values (" + "'" + person.getName() + "' ," + "'"// + person.getSex() + "'" + ")";//// try {// db.execSQL(sql);// return true;// } catch (SQLException e) {// Log.e("err", "insert failed");// return false;// } finally {// db.close();// }ContentValues values = new ContentValues();values.put("name", person.getName());values.put("sex", person.getSex());try {db.insert("employee", null, values);return true;} catch (SQLException e) {Log.e("err", "insert failed");return false;}}/*** 更新数据* * param Person*            person , int id* */public void Update(Person person, int id) {ContentValues values = new ContentValues();values.put("name", person.getName());values.put("sex", person.getSex());int rows = db.update(MyHelper.TABLE_NAME, values, "_id=?",new String[] { id + "" });}/*** 删除数据* * param int id* */public void Delete(int id) {int raw = db.delete(MyHelper.TABLE_NAME, "_id=?", new String[] { id+ "" });}/*** 查询所有数据* * */public List<Person> queryAll() {List<Person> list = new ArrayList<Person>();Cursor cursor = db.query(MyHelper.TABLE_NAME, null, null, null, null,null, null);while (cursor.moveToNext()) {Person person = new Person();person.setId(cursor.getInt(cursor.getColumnIndex("_id")));person.setName(cursor.getString(cursor.getColumnIndex("name")));person.setSex(cursor.getString(cursor.getColumnIndex("sex")));list.add(person);}return list;}/*** 按姓名进行查找并排序* * */public List<Person> queryByname(String name) {List<Person> list = new ArrayList<Person>();Cursor cursor = db.query(MyHelper.TABLE_NAME, new String[] { "_id","name", "sex" }, "name like ? ", new String[] { "%" + name+ "%" }, null, null, "name asc");while (cursor.moveToNext()) {Person person = new Person();person.setId(cursor.getInt(cursor.getColumnIndex("_id")));person.setName(cursor.getString(cursor.getColumnIndex("name")));person.setSex(cursor.getString(cursor.getColumnIndex("sex")));list.add(person);}return list;}/*** 按id查询* * */public Person queryByid(int id) {Person person = new Person();Cursor cursor = db.query(MyHelper.TABLE_NAME, new String[] { "name","sex" }, "_id=?", new String[] { id + "" }, null, null, null);while (cursor.moveToNext()) {person.setId(id);person.setName(cursor.getString(cursor.getColumnIndex("name")));person.setSex(cursor.getString(cursor.getColumnIndex("sex")));}return person;}public void close() {if (db != null) {db.close();}}
}

然后使用数据库千万记得要加权限:

  <!-- 添加SD卡读写权限 --><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

注意:我们使用数据库的时候很容易因为手动关闭数据库,然后再次操作时出现错误,所以呢我们应该在数据库操作帮助类添加关闭方法,然后在activity销毁时候调用 。

当然如果你项目中可能使用到把数据库导出为excel表格的功能:

package com.losileeya.dbsimple.tools;
import android.os.Environment;
import com.losileeya.dbsimple.bean.Person;
import java.io.File;
import java.util.List;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class JxlUtil {/*** 导出生成excel文件,存放于SD卡中* @author smart **/private List<Person> list;public JxlUtil(List<Person> list){this.list = list;}public boolean toExcel() {// 准备设置excel工作表的标题String[] title = { "编号", "姓名", "性别" };try {// 获得开始时间long start = System.currentTimeMillis();//判断SD卡是否存在if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){return false;}String SDdir =  Environment.getExternalStorageDirectory().toString();  //获取SD卡的根目录// 创建Excel工作薄WritableWorkbook wwb;// 在SD卡中,新建立一个名为person的jxl文件wwb = Workbook.createWorkbook(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/person.xls"));// 添加第一个工作表并设置第一个Sheet的名字WritableSheet sheet = wwb.createSheet("员工清单", 0);Label label;for (int i = 0; i < title.length; i++) {label = new Label(i, 0, title[i]);// 将定义好的单元格添加到工作表中sheet.addCell(label);}/** 保存数字到单元格,需要使用jxl.write.Number 必须使用其完整路径,否则会出现错误*/for(int i = 0 ; i < list.size(); i++){Person person = list.get(i);//添加编号jxl.write.Number number = new jxl.write.Number(0, i+1, person.getId());sheet.addCell(number);//添加姓名label = new Label(1,i+1,person.getName());sheet.addCell(label);//添加性别label = new Label(2,i+1,person.getSex());sheet.addCell(label);}wwb.write(); //写入数据wwb.close(); //关闭文件} catch (Exception e) {e.printStackTrace();}return true;}
}

实现这样一个功能你需要准备一个jxl.jar,过多的解释不多说。

可能大多数的情况下我们的数据一般from网络,下一篇我们就来对数据库进行封装提高一下数据库的使用效率。

demo 传送门:DbMaster

这篇关于安卓实战开发之SQLite从简单使用crud的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1131738

相关文章

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

MySQL 多列 IN 查询之语法、性能与实战技巧(最新整理)

《MySQL多列IN查询之语法、性能与实战技巧(最新整理)》本文详解MySQL多列IN查询,对比传统OR写法,强调其简洁高效,适合批量匹配复合键,通过联合索引、分批次优化提升性能,兼容多种数据库... 目录一、基础语法:多列 IN 的两种写法1. 直接值列表2. 子查询二、对比传统 OR 的写法三、性能分析

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

prometheus如何使用pushgateway监控网路丢包

《prometheus如何使用pushgateway监控网路丢包》:本文主要介绍prometheus如何使用pushgateway监控网路丢包问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录监控网路丢包脚本数据图表总结监控网路丢包脚本[root@gtcq-gt-monitor-prome

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

Python办公自动化实战之打造智能邮件发送工具

《Python办公自动化实战之打造智能邮件发送工具》在数字化办公场景中,邮件自动化是提升工作效率的关键技能,本文将演示如何使用Python的smtplib和email库构建一个支持图文混排,多附件,多... 目录前言一、基础配置:搭建邮件发送框架1.1 邮箱服务准备1.2 核心库导入1.3 基础发送函数二、

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件

PowerShell中15个提升运维效率关键命令实战指南

《PowerShell中15个提升运维效率关键命令实战指南》作为网络安全专业人员的必备技能,PowerShell在系统管理、日志分析、威胁检测和自动化响应方面展现出强大能力,下面我们就来看看15个提升... 目录一、PowerShell在网络安全中的战略价值二、网络安全关键场景命令实战1. 系统安全基线核查