使用步骤:

  1. 新建一个继承自SQLiteOpenHelper的数据库操作类,提示重写onCreate和OnUpgraed两个方法。其中,onCreate方法只在第一次打开数据库时执行,在此可进行表结构创建的操作;onUpgrade方法在数据库版本升高时执行,因此可以在onUpgraed函数内部根据新旧版本号进行表结构变更处理
  2. 封装保证数据库安全的必要方法,包括获取单例对象、打开数据库连接、关闭数据库连接
    1. 获取单例对象:确保App运行时数据库只被打开一次,避免重复打开引起错误
    2. 打开数据库连接:SQLite有锁机制,即读锁和写锁的处理;故而数据库连接也分两种,读连接可调用getReadableDatabase,写连接可调用getWritableDatabase
    3. 关闭数据库连接:数据库操作完毕后,应当调用SQLiteDatabase对象的close方法关闭连接
  3. 提供对表记录进行增加、删除、修改、查询的操作方法
    1. 可被SQLite直接使用的数据结构是ContentValues类,类似于映射Map,提供put和get方法来存取键值对。
    2. 对于查询操作来说,使用的是另一个游标类Cursor。调用SQLiteDatabase的query和rawQuery方法时,返回的都是Cursor对象,因此获取查询结果要根据游标的指示一条一条遍历结果集合。

Cursor的常用方法可分为3类:

  1. 游标控制类方法,用于指定游标的状态

    1. close:关闭游标
    2. isClosed:判断游标是否关闭
    3. isFirst:判断游标是否在开头
    4. isLast:判断游标是否在末尾
  2. 游标移动类方法,把游标移动到指定位置
    1. moveToFirst:移动游标到开头
    2. moveToLast:移动游标到末尾
    3. moveToNext:移动游标到下一条记录
    4. moveToPrevious:移动游标到上一条记录
    5. move:往后移动游标若干条记录
    6. moveToPosition:移动游标到指定位置的记录
  3. 获取记录类方法,可获取记录的数量、类型以及取值
    1. getCount:获取结果记录的数量
    2. getInt:获取指定字段的整型值
    3. getFloat
    4. getString
    5. getType
  1. public class MyDatabaseHelper extends SQLiteOpenHelper {
  2. private static final String TAG = "MyDatabaseHelper";
  3. private static final String DB_NAME = "myDB.db";
  4. private static final int DB_VERSION = 1;
  5. private static MyDatabaseHelper mHelper = null;
  6. private SQLiteDatabase mDB = null;
  7. private static final String TABLE_NAME = "my_info";
  8. private MyDatabaseHelper(Context context) {
  9. super(context, DB_NAME, null, DB_VERSION);
  10. }
  11. private MyDatabaseHelper(Context context, int version) {
  12. super(context, DB_NAME, null, version);
  13. }
  14. /**
  15. * 获取实例--单例模式
  16. * @param context
  17. * @param version
  18. * @return
  19. */
  20. public static MyDatabaseHelper getInstance(Context context, int version) {
  21. if (version > 0 && mHelper == null) {
  22. mHelper = new MyDatabaseHelper(context, version);
  23. } else if (mHelper == null) {
  24. mHelper = new MyDatabaseHelper(context);
  25. }
  26. return mHelper;
  27. }
  28. /**
  29. * 获得数据库 读 连接
  30. * @return
  31. */
  32. public SQLiteDatabase openReadLink() {
  33. if (mDB == null || mDB.isOpen() != true) {
  34. mDB = mHelper.getReadableDatabase();
  35. }
  36. return mDB;
  37. }
  38. /**
  39. * 获得数据库 写 连接
  40. * @return
  41. */
  42. public SQLiteDatabase openWriteLink() {
  43. if (mDB == null || mDB.isOpen() != true) {
  44. mDB = mHelper.getWritableDatabase();
  45. }
  46. return mDB;
  47. }
  48. /**
  49. * 关闭连接
  50. */
  51. public void closeLink() {
  52. if (mDB != null && mDB.isOpen() == true) {
  53. mDB.close();
  54. mDB = null;
  55. }
  56. }
  57. /**
  58. * 获取数据库名称
  59. * @return
  60. */
  61. public String getDBName() {
  62. if (mHelper != null) {
  63. return mHelper.getDatabaseName();
  64. } else {
  65. return DB_NAME;
  66. }
  67. }
  68. @Override
  69. public void onCreate(SQLiteDatabase db) {
  70. // 构建调用时打印sql日志
  71. Log.d(TAG, "onCreate");
  72. // 清空表数据
  73. String drop_sql = "DROP TABLE IF EXISTS " + TABLE_NAME + ";";
  74. Log.d(TAG, "drop_sql:" + drop_sql);
  75. // 执行sql
  76. db.execSQL(drop_sql);
  77. // 新建表
  78. String create_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " ("
  79. + "_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
  80. + "name VARCHAR NOT NULL," + "age INTEGER NOT NULL,"
  81. + "height LONG NOT NULL," + "weight FLOAT NOT NULL,"
  82. + "married INTEGER NOT NULL," + "update_time VARCHAR NOT NULL"
  83. //演示数据库升级时要先把下面这行注释
  84. + ",phone VARCHAR" + ",password VARCHAR"
  85. + ");";
  86. Log.d(TAG, "create_sql:" + create_sql);
  87. // 执行sql
  88. db.execSQL(create_sql);
  89. }
  90. /**
  91. * 数据库升级操作
  92. * @param db
  93. * @param oldVersion
  94. * @param newVersion
  95. */
  96. @Override
  97. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  98. Log.d(TAG, "onUpgrade oldVersion="+oldVersion+", newVersion="+newVersion);
  99. if (newVersion > 1) {
  100. //Android的ALTER命令不支持一次添加多列,只能分多次添加
  101. String alter_sql = "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + "phone VARCHAR;";
  102. Log.d(TAG, "alter_sql:" + alter_sql);
  103. db.execSQL(alter_sql);
  104. alter_sql = "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + "password VARCHAR;";
  105. Log.d(TAG, "alter_sql:" + alter_sql);
  106. db.execSQL(alter_sql);
  107. }
  108. }
  109. public int delete(String condition) {
  110. int count = mDB.delete(TABLE_NAME, condition, null);
  111. return count;
  112. }
  113. public int deleteAll() {
  114. int count = mDB.delete(TABLE_NAME, "1=1", null);
  115. return count;
  116. }
  117. public long insert(UserInfo info) {
  118. ArrayList<UserInfo> infoArray = new ArrayList<UserInfo>();
  119. infoArray.add(info);
  120. return insert(infoArray);
  121. }
  122. public long insert(ArrayList<UserInfo> infoArray) {
  123. long result = -1;
  124. for (int i = 0; i < infoArray.size(); i++) {
  125. UserInfo info = infoArray.get(i);
  126. ArrayList<UserInfo> tempArray = new ArrayList<UserInfo>();
  127. // 如果存在同名记录,则更新记录
  128. // 注意条件语句的等号后面要用单引号括起来
  129. if (info.name!=null && info.name.length()>0) {
  130. String condition = String.format("name='%s'", info.name);
  131. tempArray = query(condition);
  132. if (tempArray.size() > 0) {
  133. update(info, condition);
  134. result = tempArray.get(0).rowid;
  135. continue;
  136. }
  137. }
  138. // 如果存在同样的手机号码,则更新记录
  139. if (info.phone!=null && info.phone.length()>0) {
  140. String condition = String.format("phone='%s'", info.phone);
  141. tempArray = query(condition);
  142. if (tempArray.size() > 0) {
  143. update(info, condition);
  144. result = tempArray.get(0).rowid;
  145. continue;
  146. }
  147. }
  148. // 不存在唯一性重复的记录,则插入新记录
  149. ContentValues cv = new ContentValues();
  150. cv.put("name", info.name);
  151. cv.put("age", info.age);
  152. cv.put("height", info.height);
  153. cv.put("weight", info.weight);
  154. cv.put("married", info.married);
  155. cv.put("update_time", info.update_time);
  156. cv.put("phone", info.phone);
  157. cv.put("password", info.password);
  158. result = mDB.insert(TABLE_NAME, "", cv);
  159. // 添加成功后返回行号,失败后返回-1
  160. if (result == -1) {
  161. return result;
  162. }
  163. }
  164. return result;
  165. }
  166. public int update(UserInfo info, String condition) {
  167. ContentValues cv = new ContentValues();
  168. cv.put("name", info.name);
  169. cv.put("age", info.age);
  170. cv.put("height", info.height);
  171. cv.put("weight", info.weight);
  172. cv.put("married", info.married);
  173. cv.put("update_time", info.update_time);
  174. cv.put("phone", info.phone);
  175. cv.put("password", info.password);
  176. int count = mDB.update(TABLE_NAME, cv, condition, null);
  177. return count;
  178. }
  179. public int update(UserInfo info) {
  180. return update(info, "rowid="+info.rowid);
  181. }
  182. public ArrayList<UserInfo> query(String condition) {
  183. String sql = String.format("select rowid,_id,name,age,height,weight,married,update_time," +
  184. "phone,password from %s where %s;", TABLE_NAME, condition);
  185. Log.d(TAG, "query sql: "+sql);
  186. ArrayList<UserInfo> infoArray = new ArrayList<UserInfo>();
  187. // 获得游标对象
  188. Cursor cursor = mDB.rawQuery(sql, null);
  189. if (cursor.moveToFirst()) {
  190. for (;; cursor.moveToNext()) {
  191. UserInfo info = new UserInfo();
  192. info.rowid = cursor.getLong(0);
  193. info.xuhao = cursor.getInt(1);
  194. info.name = cursor.getString(2);
  195. info.age = cursor.getInt(3);
  196. info.height = cursor.getLong(4);
  197. info.weight = cursor.getFloat(5);
  198. //SQLite没有布尔型,用0表示false,用1表示true
  199. info.married = (cursor.getInt(6)==0)?false:true;
  200. info.update_time = cursor.getString(7);
  201. info.phone = cursor.getString(8);
  202. info.password = cursor.getString(9);
  203. infoArray.add(info);
  204. if (cursor.isLast() == true) {
  205. break;
  206. }
  207. }
  208. }
  209. cursor.close();
  210. return infoArray;
  211. }
  212. }
  1. public class UserInfo {
  2. public long rowid;
  3. public int xuhao;
  4. public String name;
  5. public int age;
  6. public long height;
  7. public float weight;
  8. public boolean married;
  9. public String update_time;
  10. public String phone;
  11. public String password;
  12. public UserInfo() {
  13. rowid = 0l;
  14. xuhao = 0;
  15. name = "";
  16. age = 0;
  17. height = 0l;
  18. weight = 0.0f;
  19. married = false;
  20. update_time = "";
  21. phone = "";
  22. password2 = "";
  23. }
  24. }

Android——SQLiteOpenHelper的更多相关文章

  1. Android SQLiteOpenHelper(二)

    上一篇我们已经了解了SQLiteOpenHelper 和 构造函数. 现在我们就来掌握一下:onCreate( )  onUpgrade( )  onDowngrade( ) public void ...

  2. Android SQLiteOpenHelper(一)

    SQLiteOpenHelper api解释: A helper class to manage database creation and version management. You creat ...

  3. Android SQLiteOpenHelper类的使用

    SQLiteOpenHelper类是Android平台提供的用于SQLite数据库的创建.打开以及版本管理的帮助类.一般需要继承并这个类并实现它的onCreate和onUpgrade方法,在构造方法中 ...

  4. android SQLiteOpenHelper使用示例

    我们大家都知道Android平台提供给我们一个数据库辅助类来创建或打开数据库,这个辅助类继承自SQLiteOpenHelper类,在该类的 构造器中,调用Context中的方法创建并打开一个指定名称的 ...

  5. android SQLiteOpenHelper 使用

    1.实体 package mydemo.mycom.demo2.entity; public class UserInfo { private int id; private String usern ...

  6. Android SQLiteOpenHelper Sqlite数据库升级onUpgrade

    Android Sqlite数据库升级,在Android APP开发之中,非常常见: 在确定原来的数据库版本号之后,在原来数据库版本号+1,就会执行onUpgrade方法,进行数据库升级操作: 在on ...

  7. Android SQLiteOpenHelper Sqlite数据库的创建与打开

    Android Sqlite数据库是一个怎样的数据库? 答:是一种嵌入式小型设备,移动设备,的数据库,应用在穿戴设备(例如:智能手表,计算手环 等等),移动设备(例如:Android系统类型的手机 等 ...

  8. Android SqliteOpenHelper详解

    一. SQLite介绍 SQLite是android内置的一个很小的关系型数据库. SQLite的官网是http://www.sqlite.org/,可以去下载一些文档或相关信息. 博客中有一篇有稍微 ...

  9. Android · SQLiteOpenHelper实例PrivateContactsDBHelper

    package privatecontact; import android.content.ContentValues; import android.content.Context; import ...

  10. 升级后开机就提示“android.process.acore”停止执行 --分析 解决方式

    OTA升级的,升级引发的全部问题都是能够解释的,有的能解决,有的不能解决. 一个项目报了这个问题. 升级后开机就提示"android.process.acore"停止执行 抓取 a ...

随机推荐

  1. MacOS Sonoma14.2.1系统SSH免密登录

    摘要:MacOS下免密登录的一些注意事项. 系统环境 操作系统:macOS Sonoma 14.2.1 SSH免密登录 ssh免密登录的原理是在本机生成本机的ssh公钥和私钥,将公钥上传至待连接的主机 ...

  2. Kernel Memory 中使用 PaddleSharp OCR

    Kernel Memory 中使用 PaddleSharp OCR Kernel Memory 中进行文档处理的时候可以上传图片作为文档,这时候就需要使用到 OCR 技术来识别图片中的文字. 官方默认 ...

  3. Apache Hudi在信息服务行业构建流批一体的实践

    个人介绍 李昂 高级数据研发工程师 Apache Doris & Hudi Contributor 业务背景 部门成立早期, 为了应对业务的快速增长, 数仓架构采用了最直接的Lambda架构 ...

  4. 2021-01-20:mysql中,一张表里有3亿数据,未分表,要求是在这个大表里添加一列数据。数据库不能停,并且还有增删改操作。请问如何操作?

    2021-01-20:mysql中,一张表里有3亿数据,未分表,要求是在这个大表里添加一列数据.数据库不能停,并且还有增删改操作.请问如何操作? 福哥答案2020-01-20: 陌陌答案: 用pt_o ...

  5. 一图看懂华为云CodeArts Link六大特性

    本文分享自华为云社区<一图看懂华为云CodeArts Link六大特性,带你体验一站式跨平台数据互联>,作者:华为云PaaS服务小智 . 能够打破不同研发工具之间的壁垒,实现数据的无缝集成 ...

  6. 带你了解NB-IoT标准演进

    摘要:本文将带大家详细了解NB-IoT标准演进与产业发展. 本文分享自华为云社区<一文带你了解NB-IoT标准演进与产业发展>,作者:万万万. 我们都知道,物联网的场景和手机.电脑在使用的 ...

  7. vue2升级vue3:class component的遗憾

    在vue2,class 写法真的非常爽 import { Component as tsc } from 'vue-tsx-support'; import { Component, Watch }  ...

  8. iOS App的打包和上架流程

    ​ 转载:iOS App的打包和上架流程 - 掘金 1. 创建账号 苹果开发者账号几种开发者账号类型 个人开发者账号 费用:99 美元/年(688.00元) 协作人数:仅限开发者自己 不需要填写公司的 ...

  9. Bert不完全手册4. 绕开BERT的MASK策略?XLNET & ELECTRA

    基于随机token MASK是Bert能实现双向上下文信息编码的核心.但是MASK策略本身存在一些问题 MASK的不一致性:MASK只在预训练任务中存在,在微调中不存在,Bert只是通过替换部分的随机 ...

  10. lab3 page tables

    1.Speed up system calls (easy) 要求:有些操作系统(例如 Linux)通过在用户空间和内核之间的只读区域共享数据来加速某些系统调用.这样可以消除在执行这些系统调用时进行内 ...