Android-SQLiteOpenHelper里增删改查
为什么要写一篇,Android-SQLiteOpenHelper里增删改查,的文章呢;
因为之前的方式是:MySQLiteOpenHelper(只负责 生成打开据库/生成打开表/升级表),在其他端:完成此数据库表的增删改查逻辑处理,这样代码有些分散
现在 MySQLiteOpenHelper(负责 生成打开据库 / 生成打开表 / 升级表 / 完成此数据库表的增删改查逻辑处理 / 还有其他表处理功能增加等等),这一个类全包了
MySQLiteOpenHelperStudent
注意事项:继承SQLiteOpenHelper抽象类 重写的创表方法,此SQLiteDatabase db 不能关闭
package liudeli.datastorage.db; import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log; import java.util.List; import liudeli.datastorage.entity.Student; /**
* 数据库表管理
* MySQLiteOpenHelperStudent
* (负责 生成打开据库 / 生成打开表 / 升级表 /
* 完成此数据库表的增删改查逻辑处理
* / 还有其他表处理功能增加等等)
*/
public class MySQLiteOpenHelperStudent extends SQLiteOpenHelper { private final static String TAG = MySQLiteOpenHelperStudent.class.getSimpleName(); /**
* 数据库名称
*/
private final static String DB_NAME = "student_info_manager.db"; /**
* 表名
*/
private static final String TABLE_NAME = "studentTable"; /**
* 定义单例模式,可以被多次地方多次调用
*/
private static MySQLiteOpenHelperStudent mySQLiteOpenHelperStudent; public static MySQLiteOpenHelperStudent getInstance(Context context) {
if (null == mySQLiteOpenHelperStudent) {
synchronized (MySQLiteOpenHelperStudent.class) {
if (null == mySQLiteOpenHelperStudent) {
mySQLiteOpenHelperStudent = new MySQLiteOpenHelperStudent(context, DB_NAME, null, 1);
}
}
}
return mySQLiteOpenHelperStudent;
} private MySQLiteOpenHelperStudent(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
} /**
* 创表方法,注意:⚠️ 传递进来的 SQLiteDatabase database 不能关闭
* @param database
*/
private void createTable(SQLiteDatabase database) {
String createTableSQL = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (ID INTEGER PRIMARY KEY, "
+ "name VARCHAR, "
+ "age INTEGER, "
+ "hobby VARCHAR);";
try {
database.execSQL(createTableSQL);
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, TAG + "创表异常:" + e.toString());
} /**
* 注意:⚠️
* 这里不能关闭database
* 一旦关闭就会 Caused by: java.lang.IllegalStateException:
* attempt to re-open an already-closed object: SQLiteDatabase:
* 为什么不能在这里关闭呢?
* 答:因为这个database,是在 public void onCreate ->传递过来的
*/
/*finally {
if (null != database) {
database.close();
}
}*/
} /**
* 删除表,会把表给删除,慎用
* drop 表
*/
public void dropTable() {
SQLiteDatabase database = getWritableDatabase();
String dropSQL = "drop table if exists " + TABLE_NAME;
try {
database.execSQL(dropSQL);
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "drop异常:" + e.toString());
} finally {
if (null != database) {
database.close();
}
}
} /**
* 清除表的数据
*/
public void cleanUpData() { // delete from TableName; //清空数据 SQLiteDatabase database = getWritableDatabase();
String cleanUpDataSQL = "delete from " + TABLE_NAME;
try {
database.execSQL(cleanUpDataSQL);
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "清除表的数据异常:" + e.toString());
} finally {
if (null != database) {
database.close();
}
}
} /**
* 插入多条数据
* @param students 传递Student集合
*/
public void insertData(List<Student> students) {
SQLiteDatabase database = getWritableDatabase();
try {
for (Student student : students) {
ContentValues contentValues = new ContentValues();
contentValues.clear();
contentValues.put("name", student.getName());
contentValues.put("age", student.getName());
contentValues.put("hobby", student.getHobby());
database.insert(TABLE_NAME, "_id", contentValues);
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "insert多条异常:" + e.toString());
} finally {
if (null != database) {
database.close();
}
}
} /**
* 插入单条
* @param contentValues 传递ContentValues
*/
public void insertData(ContentValues contentValues) {
SQLiteDatabase database = getWritableDatabase();
try {
database.insert(TABLE_NAME, "_id", contentValues);
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "insert单条异常:" + e.toString());
} finally {
if (null != database) {
database.close();
}
}
} /**
* 查询需要的列名
*/
private String[] columns = new String[]{"name", "age", "hobby"}; /**
* 查询第一条数据
* @return 返回Student实体
*/
public Student selectData() {
SQLiteDatabase database = getReadableDatabase();
Cursor cursor = null;
Student student = null;
try {
cursor = database.query(TABLE_NAME, columns, null, null, null, null, null);
if (cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
String hobby = cursor.getString(cursor.getColumnIndex("hobby")); student = new Student(name, age, hobby);
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "select异常:" + e.toString());
} finally {
if (null != database) {
database.close();
} if (null != cursor) cursor.close();
}
return student;
} /**
* 判断第一条数据是否存在
* @return 存在返回true,否则返回false
*/
public boolean isMoveToFirst() {
boolean result;
SQLiteDatabase database = getReadableDatabase();
Cursor cursor = database.query(TABLE_NAME,
columns,
null,
null,
null,
null,
null);
result = cursor.moveToFirst();
database.close();
cursor.close();
return result;
} /**
* ......... 还可以增加很多操作表相关的行为
*/ /**
* 继承SQLiteOpenHelper抽象类 重写的创表方法,此SQLiteDatabase db 不能关闭
* @param db
*/
@Override
public void onCreate(SQLiteDatabase db) {
createTable(db);
} /**
* 继承SQLiteOpenHelper抽象类 重写的升级方法
* @param db
* @param oldVersion
* @param newVersion
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
继承SQLiteOpenHelper抽象类 重写的创表方法,此SQLiteDatabase db 不能关闭
/**
* 创表方法,注意:⚠️ 传递进来的 SQLiteDatabase database 不能关闭
* @param database
*/
private void createTable(SQLiteDatabase database) {
String createTableSQL = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (ID INTEGER PRIMARY KEY, "
+ "name VARCHAR, "
+ "age INTEGER, "
+ "hobby VARCHAR);";
try {
database.execSQL(createTableSQL);
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, TAG + "创表异常:" + e.toString());
} /**
* 注意:⚠️
* 这里不能关闭database
* 一旦关闭就会 Caused by: java.lang.IllegalStateException:
* attempt to re-open an already-closed object: SQLiteDatabase:
* 为什么不能在这里关闭呢?
* 答:因为这个database,是在 public void onCreate ->传递过来的
*/
/*finally {
if (null != database) {
database.close();
}
}*/
}
一旦关闭,就会报以下错误:
Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase:


Student实体:
package liudeli.datastorage.entity;
public class Student {
private String name;
private int age;
private String hobby;
public Student() {
}
public Student(String name, int age, String hobby) {
this.name = name;
this.age = age;
this.hobby = hobby;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", hobby='" + hobby + '\'' +
'}';
}
}
测试代码:
package liudeli.datastorage; import android.app.Activity;
import android.content.ContentValues;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast; import java.util.ArrayList;
import java.util.List; import liudeli.datastorage.db.MySQLiteOpenHelperStudent;
import liudeli.datastorage.entity.Student; public class MySQLiteActivity extends Activity { private MySQLiteOpenHelperStudent mySQLiteOpenHelperStudent; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_sqlite); mySQLiteOpenHelperStudent = MySQLiteOpenHelperStudent.getInstance(this); /**
* 初始化数据
*/
ContentValues contentValues = new ContentValues();
contentValues.put("name", "刘刘" + System.currentTimeMillis());
contentValues.put("age", 26);
contentValues.put("hobby", "爱写博客" + System.currentTimeMillis()); mySQLiteOpenHelperStudent.insertData(contentValues);
} /**
* 查询
* @param view
*/
public void query(View view) {
Student student = mySQLiteOpenHelperStudent.selectData();
if (student != null) {
Log.d("sql", "student.toString:" + student.toString());
}
} /**
* 是否有第一条数据
* @param view
*/
public void query1(View view) {
Toast.makeText(this, mySQLiteOpenHelperStudent.isMoveToFirst() + "", Toast.LENGTH_LONG).show();
} /**
* drop表 删除表
* @param view
*/
public void dropTable(View view) {
mySQLiteOpenHelperStudent.dropTable();
} /**
* 插入很多数据
* @param view
*/
public void installMany(View view) {
List<Student> students = new ArrayList<>();
students.add(new Student("李李", 11, "AAAAAAA"));
students.add(new Student("李李22", 222, "BBBB"));
students.add(new Student("李李33", 333, "CCC"));
students.add(new Student("李李44", 444, "DDD"));
mySQLiteOpenHelperStudent.insertData(students);
} /**
* 清除表数据
* @param view
*/
public void cleanUpData(View view) {
mySQLiteOpenHelperStudent.cleanUpData();
}
}
测试代码的布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="query"
android:text="查询"
android:layout_weight="0"
/> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="是否有第一条数据"
android:onClick="query1"
android:layout_weight="0"
/> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="drop表 删除表"
android:onClick="dropTable"
android:layout_weight="0"
/> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="插入很多数据"
android:onClick="installMany"
android:layout_weight="0"
/> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="cleanUpData"
android:text="清除表数据"
/> </LinearLayout>
Android-SQLiteOpenHelper里增删改查的更多相关文章
- Android SQLite 数据库 增删改查操作
Android SQLite 数据库 增删改查操作 转载▼ 一.使用嵌入式关系型SQLite数据库存储数据 在Android平台上,集成了一个嵌入式关系型数据库--SQLite,SQLite3支持NU ...
- 利用SQLite在android上实现增删改查
利用SQLite在android上实现增删改查 方法: 一.直接利用database.execSQL()方法输入完整sql语句进行操作 这种方法适用于复杂的sql语句,比如多表查询等等 这里适合于增删 ...
- android 数据库的增删改查的另一种方式
老师笔记 # 3 Android下另外一种增删改查方式 1.创建一个帮助类的对象,调用getReadableDatabase方法,返回一个SqliteDatebase对象 2.使用Sq ...
- android 数据库的增删改查
主java package com.itheima.crud; import android.app.Activity; import android.content.Context; import ...
- Yii里增删改查的操作方法
一.AR $model=New user();//user是数据库中的一张表,有id,name,pwd字段 1.增加: <1. $model->name='张三': $model-> ...
- Android SQLite数据库增删改查操作
一.使用嵌入式关系型SQLite数据库存储数据 在Android平台上,集成了一个嵌入式关系型数据库——SQLite,SQLite3支持NULL.INTEGER.REAL(浮点数字). TEXT(字符 ...
- Android学习--------实现增删改查数据库操作以及实现相似微信好友对话管理操作
版权声明:本文为博主原创文章,转载请注明原文地址.谢谢~ https://blog.csdn.net/u011250851/article/details/26169409 近期的一个实验用到东西挺多 ...
- 快速入门GreenDao框架并实现增删改查案例
大家的项目中不可避免的使用到SQLite,为此我们要花费心思编写一个增删改查框架.而一个好的ORM框架则能够给我们带来极大的方便,今天给大家讲解一个非常火热的ORM-GreenDao. 基本概念 Gr ...
- Android(java)学习笔记193:利用谷歌API对数据库增删改查(推荐使用)
接下来我们通过项目案例来介绍:这个利用谷歌API对数据库增删改查 1.首先项目图: 2.这里的布局文件activity_main.xml: <LinearLayout xmlns:android ...
随机推荐
- 【推荐】开源来自百度商业前端数据可视化团队的超漂亮动态图表--ECharts
本人项目中最近有需要图表的地方,偶然发现一款超级漂亮的动态图标js图表控件,分享给大家,觉得好用的就看一下.更多更漂亮的演示大家可以参考下面两个网址:ECharts官方网址:http://ecomfe ...
- CFGym 101158B(巨坑题)
前言:无话可说,看懂题意就没什么难度了. 题意:对于[0, 9999]区间内的每一个数b,通过输入的转换表,得到一个e值,把这个值添加到b的后面,得到一个五位数c.对于c的每一位,从0枚举到9,得到5 ...
- Pthreads 读写锁
▶ 使用读写锁来限制同一数据多线程读写.若任何线程拥有读锁,则其他任何请求写锁的线程将阻塞在其写锁函数的调用上:若任何线程拥有写锁,则其他任何请求读锁和写锁的线程将阻塞在其对应的锁函数上,相当于将读与 ...
- 206. Reverse Linked List + 92. Reverse Linked List II
▶ 关于单链表翻转的两个问题. ▶ 206. 翻转整个单链表. ● 自己的代码,9 ms,使用了递归. class Solution { public: ListNode* reverseList(L ...
- java.io.CharConversionException: Not an ISO 8859-1 character:
java.io.CharConversionException: Not an ISO 8859-1 character: XXX 这个问题可能是因为outputstream输出中文字造成的影响. r ...
- 【321】python进程监控:psutil
参考:Python进程监控-MyProcMonitor 参考:Python3.6 安装psutil 模块和功能简介 参考:psutil module (Download files) 参考:廖雪峰 - ...
- .net core 一个避免跨站请求的中间件
前提: 前几天看到博客园首页中有这么一篇文章:跨站请求伪造(CSRF),刚好前段时间自己一直也在搞这个东西,后来觉得每次在form表单里添加一个@Html.AntiForgeryToken,在对应的方 ...
- 话说C# 6.0之后
最想看到的:1. 加入脚本语言支持,可以解释运行,作为程序的二次开发语言(类似于vba,python).2. 可以自定义运算符,为了安全起见,自定义运算符应该特别予以说明(类似于数学表达式,多样式的运 ...
- css常用属性总结:背景background下篇
前言:这段时间天天加班到10:30之后,简直是x了. 在上一篇文章中,分别解析了background各个属性的用法和注意细节.如果我们在项目上使用背景效果,如果使用下面的写法,你可能抓狂. body{ ...
- protobuf's custom-options
[protobuf's custom-options] protobuf可以设置属性,就像__attribute__可以给函数设置属性一样,protobuf更牛的是可以设置自定义属性.实际就是属性对象 ...