Android——SQLiteOpenHelper
使用步骤:
- 新建一个继承自SQLiteOpenHelper的数据库操作类,提示重写onCreate和OnUpgraed两个方法。其中,onCreate方法只在第一次打开数据库时执行,在此可进行表结构创建的操作;onUpgrade方法在数据库版本升高时执行,因此可以在onUpgraed函数内部根据新旧版本号进行表结构变更处理
- 封装保证数据库安全的必要方法,包括获取单例对象、打开数据库连接、关闭数据库连接
- 获取单例对象:确保App运行时数据库只被打开一次,避免重复打开引起错误
- 打开数据库连接:SQLite有锁机制,即读锁和写锁的处理;故而数据库连接也分两种,读连接可调用getReadableDatabase,写连接可调用getWritableDatabase
- 关闭数据库连接:数据库操作完毕后,应当调用SQLiteDatabase对象的close方法关闭连接
- 提供对表记录进行增加、删除、修改、查询的操作方法
- 可被SQLite直接使用的数据结构是ContentValues类,类似于映射Map,提供put和get方法来存取键值对。
- 对于查询操作来说,使用的是另一个游标类Cursor。调用SQLiteDatabase的query和rawQuery方法时,返回的都是Cursor对象,因此获取查询结果要根据游标的指示一条一条遍历结果集合。
Cursor的常用方法可分为3类:
- 游标控制类方法,用于指定游标的状态
- close:关闭游标
- isClosed:判断游标是否关闭
- isFirst:判断游标是否在开头
- isLast:判断游标是否在末尾
- 游标移动类方法,把游标移动到指定位置
- moveToFirst:移动游标到开头
- moveToLast:移动游标到末尾
- moveToNext:移动游标到下一条记录
- moveToPrevious:移动游标到上一条记录
- move:往后移动游标若干条记录
- moveToPosition:移动游标到指定位置的记录
- 获取记录类方法,可获取记录的数量、类型以及取值
- getCount:获取结果记录的数量
- getInt:获取指定字段的整型值
- getFloat
- getString
- getType
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "MyDatabaseHelper";
private static final String DB_NAME = "myDB.db";
private static final int DB_VERSION = 1;
private static MyDatabaseHelper mHelper = null;
private SQLiteDatabase mDB = null;
private static final String TABLE_NAME = "my_info";
private MyDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
private MyDatabaseHelper(Context context, int version) {
super(context, DB_NAME, null, version);
}
/**
* 获取实例--单例模式
* @param context
* @param version
* @return
*/
public static MyDatabaseHelper getInstance(Context context, int version) {
if (version > 0 && mHelper == null) {
mHelper = new MyDatabaseHelper(context, version);
} else if (mHelper == null) {
mHelper = new MyDatabaseHelper(context);
}
return mHelper;
}
/**
* 获得数据库 读 连接
* @return
*/
public SQLiteDatabase openReadLink() {
if (mDB == null || mDB.isOpen() != true) {
mDB = mHelper.getReadableDatabase();
}
return mDB;
}
/**
* 获得数据库 写 连接
* @return
*/
public SQLiteDatabase openWriteLink() {
if (mDB == null || mDB.isOpen() != true) {
mDB = mHelper.getWritableDatabase();
}
return mDB;
}
/**
* 关闭连接
*/
public void closeLink() {
if (mDB != null && mDB.isOpen() == true) {
mDB.close();
mDB = null;
}
}
/**
* 获取数据库名称
* @return
*/
public String getDBName() {
if (mHelper != null) {
return mHelper.getDatabaseName();
} else {
return DB_NAME;
}
}
@Override
public void onCreate(SQLiteDatabase db) {
// 构建调用时打印sql日志
Log.d(TAG, "onCreate");
// 清空表数据
String drop_sql = "DROP TABLE IF EXISTS " + TABLE_NAME + ";";
Log.d(TAG, "drop_sql:" + drop_sql);
// 执行sql
db.execSQL(drop_sql);
// 新建表
String create_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ "name VARCHAR NOT NULL," + "age INTEGER NOT NULL,"
+ "height LONG NOT NULL," + "weight FLOAT NOT NULL,"
+ "married INTEGER NOT NULL," + "update_time VARCHAR NOT NULL"
//演示数据库升级时要先把下面这行注释
+ ",phone VARCHAR" + ",password VARCHAR"
+ ");";
Log.d(TAG, "create_sql:" + create_sql);
// 执行sql
db.execSQL(create_sql);
}
/**
* 数据库升级操作
* @param db
* @param oldVersion
* @param newVersion
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "onUpgrade oldVersion="+oldVersion+", newVersion="+newVersion);
if (newVersion > 1) {
//Android的ALTER命令不支持一次添加多列,只能分多次添加
String alter_sql = "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + "phone VARCHAR;";
Log.d(TAG, "alter_sql:" + alter_sql);
db.execSQL(alter_sql);
alter_sql = "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + "password VARCHAR;";
Log.d(TAG, "alter_sql:" + alter_sql);
db.execSQL(alter_sql);
}
}
public int delete(String condition) {
int count = mDB.delete(TABLE_NAME, condition, null);
return count;
}
public int deleteAll() {
int count = mDB.delete(TABLE_NAME, "1=1", null);
return count;
}
public long insert(UserInfo info) {
ArrayList<UserInfo> infoArray = new ArrayList<UserInfo>();
infoArray.add(info);
return insert(infoArray);
}
public long insert(ArrayList<UserInfo> infoArray) {
long result = -1;
for (int i = 0; i < infoArray.size(); i++) {
UserInfo info = infoArray.get(i);
ArrayList<UserInfo> tempArray = new ArrayList<UserInfo>();
// 如果存在同名记录,则更新记录
// 注意条件语句的等号后面要用单引号括起来
if (info.name!=null && info.name.length()>0) {
String condition = String.format("name='%s'", info.name);
tempArray = query(condition);
if (tempArray.size() > 0) {
update(info, condition);
result = tempArray.get(0).rowid;
continue;
}
}
// 如果存在同样的手机号码,则更新记录
if (info.phone!=null && info.phone.length()>0) {
String condition = String.format("phone='%s'", info.phone);
tempArray = query(condition);
if (tempArray.size() > 0) {
update(info, condition);
result = tempArray.get(0).rowid;
continue;
}
}
// 不存在唯一性重复的记录,则插入新记录
ContentValues cv = new ContentValues();
cv.put("name", info.name);
cv.put("age", info.age);
cv.put("height", info.height);
cv.put("weight", info.weight);
cv.put("married", info.married);
cv.put("update_time", info.update_time);
cv.put("phone", info.phone);
cv.put("password", info.password);
result = mDB.insert(TABLE_NAME, "", cv);
// 添加成功后返回行号,失败后返回-1
if (result == -1) {
return result;
}
}
return result;
}
public int update(UserInfo info, String condition) {
ContentValues cv = new ContentValues();
cv.put("name", info.name);
cv.put("age", info.age);
cv.put("height", info.height);
cv.put("weight", info.weight);
cv.put("married", info.married);
cv.put("update_time", info.update_time);
cv.put("phone", info.phone);
cv.put("password", info.password);
int count = mDB.update(TABLE_NAME, cv, condition, null);
return count;
}
public int update(UserInfo info) {
return update(info, "rowid="+info.rowid);
}
public ArrayList<UserInfo> query(String condition) {
String sql = String.format("select rowid,_id,name,age,height,weight,married,update_time," +
"phone,password from %s where %s;", TABLE_NAME, condition);
Log.d(TAG, "query sql: "+sql);
ArrayList<UserInfo> infoArray = new ArrayList<UserInfo>();
// 获得游标对象
Cursor cursor = mDB.rawQuery(sql, null);
if (cursor.moveToFirst()) {
for (;; cursor.moveToNext()) {
UserInfo info = new UserInfo();
info.rowid = cursor.getLong(0);
info.xuhao = cursor.getInt(1);
info.name = cursor.getString(2);
info.age = cursor.getInt(3);
info.height = cursor.getLong(4);
info.weight = cursor.getFloat(5);
//SQLite没有布尔型,用0表示false,用1表示true
info.married = (cursor.getInt(6)==0)?false:true;
info.update_time = cursor.getString(7);
info.phone = cursor.getString(8);
info.password = cursor.getString(9);
infoArray.add(info);
if (cursor.isLast() == true) {
break;
}
}
}
cursor.close();
return infoArray;
}
}
public class UserInfo {
public long rowid;
public int xuhao;
public String name;
public int age;
public long height;
public float weight;
public boolean married;
public String update_time;
public String phone;
public String password;
public UserInfo() {
rowid = 0l;
xuhao = 0;
name = "";
age = 0;
height = 0l;
weight = 0.0f;
married = false;
update_time = "";
phone = "";
password2 = "";
}
}
Android——SQLiteOpenHelper的更多相关文章
- Android SQLiteOpenHelper(二)
上一篇我们已经了解了SQLiteOpenHelper 和 构造函数. 现在我们就来掌握一下:onCreate( ) onUpgrade( ) onDowngrade( ) public void ...
- Android SQLiteOpenHelper(一)
SQLiteOpenHelper api解释: A helper class to manage database creation and version management. You creat ...
- Android SQLiteOpenHelper类的使用
SQLiteOpenHelper类是Android平台提供的用于SQLite数据库的创建.打开以及版本管理的帮助类.一般需要继承并这个类并实现它的onCreate和onUpgrade方法,在构造方法中 ...
- android SQLiteOpenHelper使用示例
我们大家都知道Android平台提供给我们一个数据库辅助类来创建或打开数据库,这个辅助类继承自SQLiteOpenHelper类,在该类的 构造器中,调用Context中的方法创建并打开一个指定名称的 ...
- android SQLiteOpenHelper 使用
1.实体 package mydemo.mycom.demo2.entity; public class UserInfo { private int id; private String usern ...
- Android SQLiteOpenHelper Sqlite数据库升级onUpgrade
Android Sqlite数据库升级,在Android APP开发之中,非常常见: 在确定原来的数据库版本号之后,在原来数据库版本号+1,就会执行onUpgrade方法,进行数据库升级操作: 在on ...
- Android SQLiteOpenHelper Sqlite数据库的创建与打开
Android Sqlite数据库是一个怎样的数据库? 答:是一种嵌入式小型设备,移动设备,的数据库,应用在穿戴设备(例如:智能手表,计算手环 等等),移动设备(例如:Android系统类型的手机 等 ...
- Android SqliteOpenHelper详解
一. SQLite介绍 SQLite是android内置的一个很小的关系型数据库. SQLite的官网是http://www.sqlite.org/,可以去下载一些文档或相关信息. 博客中有一篇有稍微 ...
- Android · SQLiteOpenHelper实例PrivateContactsDBHelper
package privatecontact; import android.content.ContentValues; import android.content.Context; import ...
- 升级后开机就提示“android.process.acore”停止执行 --分析 解决方式
OTA升级的,升级引发的全部问题都是能够解释的,有的能解决,有的不能解决. 一个项目报了这个问题. 升级后开机就提示"android.process.acore"停止执行 抓取 a ...
随机推荐
- 网安区过年-Log4j2
Log4j2-2021 漏洞原理 Apache Log4j 2 是Java语言的日志处理套件,使用极为广泛.在其2.0到2.14.1版本中存在一处JNDI注入漏洞,攻击者在可以控制日志内容的情况下,通 ...
- 解决QObject::moveToThread: Current thread (0x56059f9b0f70) is not the object's t
对 opencv 降级 pip install opencv-python==4.1.2.30
- C#数据结构与算法系列(十三):递归——迷宫问题
1.示例 2.代码实现 public class Maze { public static void Test() { int[][] map = new int[8][]; for (int i = ...
- 六步带你完成博流wifi模组对接华为云流程
摘要:本文主要采用基于博流wifi模组以及我们的SDK移植实现华为云的对接,上报数据以及命令下发等,希望对您有所帮助. 1 简介 首先需要研究透彻博流项目的编译运行流程,首先看其根目录中包括compo ...
- 开发老人笔记:Git 常用命令清单
摘要:git是目前世界上最先进的分布式版本控制系统. 多人协作 master:此分支用来发布稳定的代码,合并一般是由管理员合并 dev:此分支用于团队开发,团队成员向此分支提交代码 bug:此分支用于 ...
- MPU:鸿蒙轻内核的任务栈的溢出检察官
摘要:MPU(Memory Protection Unit,内存保护单元)把内存映射为一系列内存区域,定义这些内存区域的维洲,大小,访问权限和内存熟悉信息. 本文分享自华为云社区<鸿蒙轻内核M核 ...
- 华为云企业级Redis:助力VMALL打造先进特征平台
摘要:当电商平台对AI算法模型的需求越来越多,特征数据平台的统一建设是不少开发团队头疼的事情.因为只有通过统一的特征数据存储,才能改变原有的"数据孤岛",解决生产重复造轮子的窘境. ...
- Pycharts在测试工作中的应用
Pycharts在测试工作中的应用 pycharts是一个基于Python的数据可视化库,支持多种折线图.柱状图.饼图等.Pycharts底层依赖于Echarts pip install pyecha ...
- vue 基础学习 一
1. vue 使用快速入门三步走 (1) 新建 HTML 页面,引入 Vue.js文件 <!DOCTYPE html> <html> <head> <meta ...
- mit6.s081 lab2: system calls
1.system call tracing(moderate) 要求:创建一个系统调用来实现跟踪特性,它采用一个参数来指定跟踪哪一个系统调用,例如:跟踪fork系统调用,程序调用trace(1< ...