SQLiteDatabase
管理类,用于数据库层面的操作。
- openDatabase:打开指定路径的数据库。
- isOpen:判断数据库是否已打开。
- close:关闭数据库。
- getVersion:获取数据库的版本号。
- setVersion:设置数据库的版本号。
事务类,用于事务层面的操作。
- beginTransaction:开始事务。
- setTransactionSuccessful:设置事务的成功标志。
- endTransaction:结束事务。
数据处理类,用于数据表层面的操作。
- execSQL:执行拼接好的SQL控制语句。
- delete:删除符合条件的记录。
- update:更新符合条件的记录。
- insert:插入一条记录。
- query:执行查询操作,返回结果集的游标。
- rawQuery:执行拼接好的SQL查询语句,返回结果集的游标
SQLiteOpenHelper
新建一个继承自 SQLiteOpenHelper 的数据库操作类,提示重写 onCreate 和 onUpgrade 两个方 法。
- 封装保证数据库安全的必要方法。
- 提供对表记录进行增加、删除、修改、查询的操作方法
展示
查询
实体类
User.java
package com.example.datastorage.enity;
public class User {
public int id; // 序号
public String name; // 姓名
public int age; // 年龄
public long height; // 身高
public float weight; // 体重
public boolean married; // 婚否
public User(){
}
public User(String name, int age, long height, float weight, boolean married) {
this.name = name;
this.age = age;
this.height = height;
this.weight = weight;
this.married = married;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", height=" + height +
", weight=" + weight +
", married=" + married +
'}';
}
}
增删改查类
UserHelper.java
package com.example.datastorage.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.datastorage.enity.User;
import java.util.ArrayList;
import java.util.List;
public class UserHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "user.db";
private static final String TABLE_NAME = "user_info";
private static final int DB_VERSION = 2;
private static UserHelper mHelper = null;
private SQLiteDatabase mRDB = null;
private SQLiteDatabase mWDB = null;
private UserHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
// 利用单例模式获取数据库帮助器的唯一实例
public static UserHelper getInstance(Context context) {
if (mHelper == null) {
mHelper = new UserHelper(context);
}
return mHelper;
}
// 打开数据库的读连接
public SQLiteDatabase openReadLink() {
if (mRDB == null || !mRDB.isOpen()) {
mRDB = mHelper.getReadableDatabase();
}
return mRDB;
}
// 打开数据库的写连接
public SQLiteDatabase openWriteLink() {
if (mWDB == null || !mWDB.isOpen()) {
mWDB = mHelper.getWritableDatabase();
}
return mWDB;
}
// 关闭数据库连接
public void closeLink() {
if (mRDB != null && mRDB.isOpen()) {
mRDB.close();
mRDB = null;
}
if (mWDB != null && mWDB.isOpen()) {
mWDB.close();
mWDB = null;
}
}
// 创建数据库,执行建表语句
@Override
public void onCreate(SQLiteDatabase db) {
String 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);";
db.execSQL(sql);
}
/**
* 添加字段
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "ALTER TABLE " + TABLE_NAME + " ADD COLUMN phone VARCHAR;";
db.execSQL(sql);
sql = "ALTER TABLE " + TABLE_NAME + " ADD COLUMN password VARCHAR;";
db.execSQL(sql);
}
/**
* 添加
* @param user
* @return 1
*/
public long insert(User user) {
ContentValues values = new ContentValues();
values.put("name", user.name);
values.put("age", user.age);
values.put("height", user.height);
values.put("weight", user.weight);
values.put("married", user.married);
// 执行插入记录动作,该语句返回插入记录的行号
// 如果第三个参数values 为Null或者元素个数为0, 由于insert()方法要求必须添加一条除了主键之外其它字段为Null值的记录,
// 为了满足SQL语法的需要, insert语句必须给定一个字段名 ,如:insert into person(name) values(NULL),
// 倘若不给定字段名 , insert语句就成了这样: insert into person() values(),显然这不满足标准SQL的语法。
// 如果第三个参数values 不为Null并且元素的个数大于0 ,可以把第二个参数设置为null 。
//return mWDB.insert(TABLE_NAME, null, values);
try {
mWDB.beginTransaction();
mWDB.insert(TABLE_NAME, null, values);
//int i = 10 / 0;
mWDB.insert(TABLE_NAME, null, values);
mWDB.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
mWDB.endTransaction();
}
return 1;
}
/**
* 通过名字进行删除
* @param name
* @return User
*/
public long deleteByName(String name) {
//删除所有
//mWDB.delete(TABLE_NAME, "1=1", null);
return mWDB.delete(TABLE_NAME, "name=?", new String[]{name});
}
/**
* 修改
* @param user
* @return User
*/
public long update(User user) {
ContentValues values = new ContentValues();
values.put("name", user.name);
values.put("age", user.age);
values.put("height", user.height);
values.put("weight", user.weight);
values.put("married", user.married);
return mWDB.update(TABLE_NAME, values, "name=?", new String[]{user.name});
}
/**
* 查询
* @return
*/
public List queryAll() {
List list = new ArrayList<>();
// 执行记录查询动作,该语句返回结果集的游标
Cursor cursor = mRDB.query(TABLE_NAME, null, null, null, null, null, null);
// 循环取出游标指向的每条记录
while (cursor.moveToNext()) {
User user = new User();
user.id = cursor.getInt(0);
user.name = cursor.getString(1);
user.age = cursor.getInt(2);
user.height = cursor.getLong(3);
user.weight = cursor.getFloat(4);
//SQLite没有布尔型,用0表示false,用1表示true
user.married = (cursor.getInt(5) == 0) ? false : true;
list.add(user);
}
return list;
}
public List queryByName(String name) {
List list = new ArrayList<>();
// 执行记录查询动作,该语句返回结果集的游标
Cursor cursor = mRDB.query(TABLE_NAME, null, "name=?", new String[]{name}, null, null, null);
// 循环取出游标指向的每条记录
while (cursor.moveToNext()) {
User user = new User();
user.id = cursor.getInt(0);
user.name = cursor.getString(1);
user.age = cursor.getInt(2);
user.height = cursor.getLong(3);
user.weight = cursor.getFloat(4);
//SQLite没有布尔型,用0表示false,用1表示true
user.married = (cursor.getInt(5) == 0) ? false : true;
list.add(user);
}
return list;
}
}
逻辑处理
SQLiteHelperActivity.java
package com.example.datastorage;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import com.example.datastorage.database.UserHelper;
import com.example.datastorage.enity.User;
import com.example.datastorage.util.ToastUtil;
import java.util.List;
public class SQLHelperActivity extends AppCompatActivity implements View.OnClickListener {
private EditText et_name;
private EditText et_age;
private EditText et_height;
private EditText et_weight;
private CheckBox ck_married;
private UserHelper mHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sqlhelper);
et_name = findViewById(R.id.et_name);
et_age = findViewById(R.id.et_age);
et_height = findViewById(R.id.et_height);
et_weight = findViewById(R.id.et_weight);
ck_married = findViewById(R.id.ck_married);
findViewById(R.id.btn_save).setOnClickListener(this);
findViewById(R.id.btn_delete).setOnClickListener(this);
findViewById(R.id.btn_update).setOnClickListener(this);
findViewById(R.id.btn_query).setOnClickListener(this);
}
@Override
protected void onStart() {
super.onStart();
// 获得数据库帮助器的实例
mHelper = UserHelper.getInstance(this);
// 打开数据库帮助器的读写连接
mHelper.openWriteLink();
mHelper.openReadLink();
}
@Override
protected void onStop() {
super.onStop();
// 关闭数据库连接
mHelper.closeLink();
}
@Override
public void onClick(View v) {
String name = et_name.getText().toString();
String age = et_age.getText().toString();
String height = et_height.getText().toString();
String weight = et_weight.getText().toString();
User user = null;
switch (v.getId()) {
case R.id.btn_save:
// 以下声明一个用户信息对象,并填写它的各字段值
user = new User(name,
Integer.parseInt(age),
Long.parseLong(height),
Float.parseFloat(weight),
ck_married.isChecked());
if (mHelper.insert(user) > 0) {
ToastUtil.show(this, "添加成功");
}
break;
case R.id.btn_delete:
if (mHelper.deleteByName(name) > 0) {
ToastUtil.show(this, "删除成功");
}
break;
case R.id.btn_update:
user = new User(name,
Integer.parseInt(age),
Long.parseLong(height),
Float.parseFloat(weight),
ck_married.isChecked());
if (mHelper.update(user) > 0) {
ToastUtil.show(this, "修改成功");
}
break;
case R.id.btn_query:
List list = mHelper.queryAll();
//List list = mHelper.queryByName(name);
for (User u : list) {
Log.d("kcs", u.toString());
}
break;
}
}
}
Original: https://blog.csdn.net/qq_56098191/article/details/126265079
Author: 猫十二懿
Title: Android -SQLite 的增删改查(CRUD)
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/816413/
转载文章受原作者版权保护。转载请注明原作者出处!