SQLiteOpenHelper数据库帮助器

embedded/2024/9/25 15:24:52/

SQLiteOpenHelper数据库帮助器是Android提供的数据库辅助工具。

1、继承SQLiteOpenHelper类,需要重写onCreate和onUpgrade两个方法

案例:实现增删改查

package com.example.databases_text;import android.app.PictureInPictureParams;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.Rational;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import com.example.databases_text.R;import java.util.List;public class MainActivity extends AppCompatActivity implements View.OnClickListener{private EditText edit_name;private  EditText edit_password;private UserDBHelper mUserDBHelper;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);edit_name=findViewById(R.id.et_name);edit_password=findViewById(R.id.et_pws);findViewById(R.id.btn_add).setOnClickListener(this);findViewById(R.id.btn_del).setOnClickListener(this);findViewById(R.id.btn_update).setOnClickListener(this);findViewById(R.id.btn_query).setOnClickListener(this);}@Overrideprotected void onStart() {super.onStart();//获得数据库帮助器实例mUserDBHelper = UserDBHelper.getInstance(this);mUserDBHelper.openWriteLink();//打开数据库mUserDBHelper.openReadLink();}@Overrideprotected void onDestroy() {super.onDestroy();}@Overridepublic void onClick(View view) {User user = new User();String name=edit_name.getText().toString();String psw=edit_password.getText().toString();switch (view.getId()){case R.id.btn_add:user.setName(name);user.setPassword(psw);if( mUserDBHelper.InsertData(user)>0)Toast.makeText(this,"添加成功", Toast.LENGTH_SHORT).show();break;case R.id.btn_del:user.setName(name);user.setPassword(psw);if( mUserDBHelper.deleteData(user)>0)Toast.makeText(this,"删除成功", Toast.LENGTH_SHORT).show();break;case R.id.btn_update:user.setName(name);user.setPassword(psw);if( mUserDBHelper.updateData(user)>0)Toast.makeText(this,"修改成功", Toast.LENGTH_SHORT).show();break;case R.id.btn_query:List<User> userList=mUserDBHelper.queryData(name);if(userList !=null){edit_password.setText(userList.get(0).getPassword());//userList.get(x).getPassword()表示查询第几个的密码Toast.makeText(this,"查询成功", Toast.LENGTH_SHORT).show();}break;}}
}
package com.example.databases_text;public class User {private  String name;private String password;public User() {}public User(String name, String password) {this.name = name;this.password = password;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return "User{" +"name='" + name + '\'' +", password='" + password + '\'' +'}';}
}
package com.example.databases_text;import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;import java.util.ArrayList;
import java.util.List;public class UserDBHelper extends SQLiteOpenHelper {// 数据库版本号public static final int DATABASE_VERSION = 1;// 数据库名称public static final String DATABASE_NAME = "User.db";public static final String DATABASE_table_name = "uer_table";// 用户表名public static final String TABLE_NAME = "user";// 用户名public static final String COLUMN_NAME = "name";// 用户密码public static final String COLUMN_PASSWORD = "password";private static UserDBHelper instance=null;private SQLiteDatabase mRDB=null;private SQLiteDatabase mWDB=null;public UserDBHelper( Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);}//利用单例模式,获取数据库的唯一实例,当数据库不存在的时候,经行创建,如果已存在就直接返回public static UserDBHelper getInstance(Context context){if(instance==null){instance=new UserDBHelper(context);}return  instance;}//打开数据库的读连接public SQLiteDatabase openReadLink(){if(mRDB==null || !mRDB.isOpen()) {mRDB = instance.getReadableDatabase();}return mRDB;}//打开数据库的写连接public SQLiteDatabase openWriteLink(){if(mWDB==null || !mWDB.isOpen()) {mWDB = instance.getReadableDatabase();}return mWDB;}//数据库的关闭操作public void closeLink() {if (mRDB != null && mRDB.isOpen()) {mRDB.close();mRDB = null;}if (mWDB != null && mWDB.isOpen()) {mWDB.close();mWDB = null;//置为空为了回收}}//创建数据库,执行sql语句@Overridepublic void onCreate(SQLiteDatabase sqLiteDatabase) {String sql = "create table " + TABLE_NAME + " (" + COLUMN_NAME + " text, " + COLUMN_PASSWORD+ " text)";sqLiteDatabase.execSQL(sql);}@Overridepublic void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {}//添加数据到数据库public long InsertData(User user){ContentValues values = new ContentValues();values.put("name", user.getName());values.put("password", user.getPassword());return   mWDB.insert(TABLE_NAME,null,values);}public long deleteData(User user){//删除所有的return mWDB.delete(TABLE_NAME,"name=? and password=?",new String[]{user.getName(),user.getPassword()});}public long updateData(User user){ContentValues values = new ContentValues();values.put("name", user.getName());values.put("password", user.getPassword());//更改所有符合条件的数据return mWDB.update(TABLE_NAME,values,"name=? ",new String[]{user.getName()});}public List<User> queryData(String name){List<User> list = new ArrayList<>();//查询所有数据,得到游标Cursor cursor =mWDB.query(TABLE_NAME,null,"name=? ",new String[]{name},null,null,null);//逐个取出游标指向的数据while (cursor.moveToNext()){User user1=new User();user1.setName(cursor.getString(0));user1.setPassword(cursor.getString(1));list.add(user1);}return list;}}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"android:orientation="vertical"><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:text="用户名"/><EditTextandroid:id="@+id/et_name"android:layout_width="match_parent"android:layout_height="wrap_content"/><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:text="密码"/><EditTextandroid:id="@+id/et_pws"android:layout_width="match_parent"android:layout_height="wrap_content"/><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/btn_add"android:text="添加"/><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/btn_del"android:text="删除"/><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/btn_update"android:text="修改"/><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/btn_query"android:text="查询"/>
</LinearLayout>

2、onUpgrade()是在数据库版本更新时,执行操作。


http://www.ppmy.cn/embedded/43308.html

相关文章

探索数字规律与数组操作

新书上架~&#x1f447;全国包邮奥~ python实用小工具开发教程http://pythontoolsteach.com/3 欢迎关注我&#x1f446;&#xff0c;收藏下次不迷路┗|&#xff40;O′|┛ 嗷~~ 目录 一、问题描述与需求概述 二、数字规律的理解 1. 观察数字模式 2. 思考生成方法 三、实现…

在vue中实现下载文件功能

实际操作为&#xff0c;在表格中 我们可以获取到文件的id&#xff0c;通过插槽就可以实现 <template #default"scope"><el-button type"text" click"handleDown(scope.row)"><span>下载</span></el-button> </…

Java技术精粹:高级面试问题与解答指南(一)

Java 面试问题及答案 问题1&#xff1a;请解释Java中的多态性&#xff0c;并给出一个例子。 答案&#xff1a; 多态性是Java中的一个重要特性&#xff0c;它允许一个引用类型可以指向多种实际类型的对象&#xff0c;并且可以通过这个引用调用实际对象的方法。多态性主要通过继…

NV-LIO:一种基于法向量的激光雷达-惯性系统(LIO)

论文&#xff1a;NV-LIO: LiDAR-Inertial Odometry using Normal Vectors Towards Robust SLAM in Multifloor Environments 作者&#xff1a;Dongha Chung, Jinwhan Kim NV-LIO&#xff1a;一种基于法向量的激光雷达-惯性系统&#xff08;LIO&#xff09;NV-LIO利用从激光雷…

设计模式基础——设计原则介绍

1.概述 ​ 对于面向对象软件系统的设计而言&#xff0c;如何同时提高一个软件系统的可维护性、可复用性、可拓展性是面向对象设计需要解决的核心问题之一。面向对象设计原则应运而生&#xff0c;这些原则你会在设计模式中找到它们的影子&#xff0c;也是设计模式的基础。往往判…

【全开源】JAVA同城搬家系统源码小程序APP源码

JAVA同城搬家系统源码 特色功能&#xff1a; 强大的数据处理能力&#xff1a;JAVA提供了丰富的数据结构和算法&#xff0c;以及强大的并发处理能力&#xff0c;使得系统能够快速地处理大量的货物信息、司机信息、订单信息等&#xff0c;满足大规模物流的需求。智能路径规划&a…

React hooks - 自定义hooks

自定义hooks 自定义封装鼠标位置的 hook自定义封装秒数倒计时的 hook 在 src 目录下新建 hooks/index.ts 模块&#xff0c;自定义hooks都写在这里&#xff0c;自定义hooks都以use开头 自定义封装鼠标位置的 hook export const useMousePosition (delay:number 0) > {cons…

从华为云Redis到AWS ElastiCache的操作方法

越来越多企业选择出海&#xff0c;那么就涉及到IT系统的迁移&#xff0c;本文将详细介绍如何将华为云Redis顺利迁移到AWS ElastiCache的操作方法&#xff0c;九河云将为您介绍迁移步骤以帮助您顺利完成这一重要任务。 **1. 确定迁移计划** 在开始迁移之前&#xff0c;首先要制…