ToB企服应用市场:ToB评测及商务社交产业平台

标题: Android Studio 数据库Sqlite3 安卓工具类(简便开发) [打印本页]

作者: 美食家大橙子    时间: 2024-12-25 09:05
标题: Android Studio 数据库Sqlite3 安卓工具类(简便开发)
目录
一、数据库检察方式
二、封装工具类
三、使用Sqlite工具类(直接调用)
1.增
2.删
3.改
4.查


   版本:Android Studio 2024.1.1
  SDK:34
  一、数据库检察方式

使用App Inspection工具,此工具包括网络哀求、数据库访问等功能,可以实时监控应用的行为。
如图所示:



二、封装工具类

源码:
DatabaseHelper.java
  1. package com.example.mytest;   //注意:替换成自己的包名
  2. import android.content.ContentValues;
  3. import android.content.Context;
  4. import android.database.Cursor;
  5. import android.database.sqlite.SQLiteDatabase;
  6. import android.database.sqlite.SQLiteException;
  7. import android.database.sqlite.SQLiteOpenHelper;
  8. import android.util.Log;
  9. import androidx.annotation.Nullable;
  10. import java.util.List;
  11. import java.util.ArrayList;
  12. public class DatabaseHelper extends SQLiteOpenHelper {
  13.     private static final String TAG = "DatabaseHelper";
  14.     //数据库名和版本号
  15.     private static final String DATABASE_NAME = "test.db";
  16.     private static final int DATABASE_VERSION = 1;
  17.     //单例对象
  18.     private static DatabaseHelper instance;
  19.     private DatabaseHelper(@Nullable Context context) {
  20.         super(context, DATABASE_NAME, null, DATABASE_VERSION);
  21.         Log.d(TAG,"DatabaseHelper");
  22.     }
  23.     //单例模式获取实例
  24.     public static synchronized DatabaseHelper getInstance(Context context){
  25.         if(instance == null){
  26.             instance = new DatabaseHelper(context.getApplicationContext());
  27.             Log.d(TAG,"getInstance");
  28.         }
  29.         return instance;
  30.     }
  31.     @Override
  32.     public void onCreate(SQLiteDatabase sqLiteDatabase) {
  33.         String sql = "CREATE TABLE user (" +
  34.                 "id INTEGER PRIMARY KEY AUTOINCREMENT," +
  35.                 "username TEXT NOT NULL," +
  36.                 "password TEXT NOT NULL," +
  37.                 "age INTEGER," +
  38.                 "height REAL," +
  39.                 "is_active BOOLEAN NOT NULL DEFAULT 1," +
  40.                 "created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP" +
  41.                 ");";
  42.         Log.d(TAG,sql);
  43.         sqLiteDatabase.execSQL(sql);
  44.     }
  45.     @Override
  46.     public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
  47.     }
  48.     //增加数据,返回值为-1代表插入失败
  49.     public long insertUser(String username, String password, int age, double height, boolean isActive) {
  50.         SQLiteDatabase db = instance.getWritableDatabase();
  51.         long ret = 0;
  52.         try {
  53.             // 组装数据插入
  54.             ContentValues values = new ContentValues();
  55.             values.put("username", username);
  56.             values.put("password", password);
  57.             values.put("age", age);
  58.             values.put("height", height);
  59.             values.put("is_active", isActive ? 1 : 0);
  60.             ret = db.insert("user", null, values);
  61.         } catch (SQLiteException e) {
  62.             // 处理数据库操作失败的情况
  63.             Log.e(TAG, "Failed to insertUser : " , e);
  64.         } finally {
  65.             //关闭数据库,    注意:使用App Inspection调试时不执行db.close();,否则无法调试
  66.             db.close();
  67.         }
  68.         return ret;
  69.     }
  70.     //删除数据
  71.     public void deleteUser(long id) {
  72.         SQLiteDatabase db = instance.getWritableDatabase();
  73.         try {
  74.             // 使用参数化查询防止 SQL 注入
  75.             String selection = "id = ?";
  76.             String[] selectionArgs = { String.valueOf(id) };
  77.             db.delete("user", selection, selectionArgs);
  78.         } catch (SQLiteException e) {
  79.             // 处理数据库操作失败的情况
  80.             Log.e(TAG, "Failed to delete user with ID: " + id, e);
  81.         } finally {
  82.             //关闭数据库,   注意:使用App Inspection调试时不执行db.close();,否则无法调试
  83.             db.close();
  84.         }
  85.     }
  86.     //修改数据,返回值 <0 代表失败
  87.     public int updateUser(long id, String username, String password, int age, double height, boolean isActive) {
  88.         SQLiteDatabase db = instance.getWritableDatabase();
  89.         int ret = 0;
  90.         try {
  91.             // 组装数据插入
  92.             ContentValues values = new ContentValues();
  93.             values.put("username", username);
  94.             values.put("password", password);
  95.             values.put("age", age);
  96.             values.put("height", height);
  97.             values.put("is_active", isActive ? 1 : 0);
  98.             String selection = "id LIKE ?";
  99.             String[] selectionArgs = { String.valueOf(id) };
  100.             ret = db.update("user", values, selection, selectionArgs);
  101.         } catch (SQLiteException e) {
  102.             // 处理数据库操作失败的情况
  103.             Log.e(TAG, "Failed to insertUser : " , e);
  104.         } finally {
  105.             //关闭数据库,  注意:使用App Inspection调试时不执行,否则看不到实时数据
  106.             db.close();
  107.         }
  108.         return ret;
  109.     }
  110.     //查询数据,所有
  111.     public List<UserBean> getAllUsers() {
  112.         SQLiteDatabase db = instance.getReadableDatabase();
  113.         List<UserBean> userList = new ArrayList<>();
  114.         // 执行查询
  115.         Cursor cursor = db.query("user", null, null, null, null, null, null);
  116.         if (cursor.moveToFirst()) {
  117.             do {
  118.                 long id = cursor.getLong(cursor.getColumnIndex("id"));
  119.                 String username = cursor.getString(cursor.getColumnIndex("username"));
  120.                 String password = cursor.getString(cursor.getColumnIndex("password"));
  121.                 int age = cursor.getInt(cursor.getColumnIndex("age"));
  122.                 float height = cursor.getFloat(cursor.getColumnIndex("height"));
  123.                 boolean isActive = cursor.getInt(cursor.getColumnIndex("is_active")) == 1;
  124.                 long createdTime = cursor.getLong(cursor.getColumnIndex("created_time"));
  125.                 UserBean user = new UserBean(id, username, password, age, height, isActive, createdTime);
  126.                 userList.add(user);
  127.             } while (cursor.moveToNext());
  128.         }
  129.         cursor.close();
  130.         db.close();
  131.         return userList;
  132.     }
  133.     //查询数据,指定
  134.     public UserBean getUserById(long userId) {
  135.         SQLiteDatabase db = instance.getReadableDatabase();
  136.         // 定义查询条件
  137.         String selection = "id = ?";
  138.         String[] selectionArgs = { String.valueOf(userId) };
  139.         //执行查询
  140.         Cursor cursor = db.query("user", null, selection, selectionArgs, null, null, null);
  141.         UserBean user = null;
  142.         if (cursor.moveToFirst()) {
  143.             long id = cursor.getLong(cursor.getColumnIndex("id"));
  144.             String username = cursor.getString(cursor.getColumnIndex("username"));
  145.             String password = cursor.getString(cursor.getColumnIndex("password"));
  146.             int age = cursor.getInt(cursor.getColumnIndex("age"));
  147.             float height = cursor.getFloat(cursor.getColumnIndex("height"));
  148.             boolean isActive = cursor.getInt(cursor.getColumnIndex("is_active")) == 1;
  149.             long createdTime = cursor.getLong(cursor.getColumnIndex("created_time"));
  150.             user = new UserBean(id, username, password, age, height, isActive, createdTime);
  151.         }
  152.         cursor.close();
  153.         db.close();
  154.         return user;
  155.     }
  156. }
复制代码

实体类界说,查询使用,只用增、删、改 不消添加。
UserBean .java
  1. package com.example.mytest;        //替换成自己包名
  2. public class UserBean {
  3.     private long id;
  4.     private String username;
  5.     private String password;
  6.     private int age;
  7.     private float height;
  8.     private boolean isActive;
  9.     private long createdTime;
  10.     // 构造函数
  11.     public UserBean(long id, String username, String password, int age, float height, boolean isActive, long createdTime) {
  12.         this.id = id;
  13.         this.username = username;
  14.         this.password = password;
  15.         this.age = age;
  16.         this.height = height;
  17.         this.isActive = isActive;
  18.         this.createdTime = createdTime;
  19.     }
  20.     // Getter 和 Setter 方法
  21.     public long getId() {
  22.         return id;
  23.     }
  24.     public void setId(long id) {
  25.         this.id = id;
  26.     }
  27.     public String getUsername() {
  28.         return username;
  29.     }
  30.     public void setUsername(String username) {
  31.         this.username = username;
  32.     }
  33.     public String getPassword() {
  34.         return password;
  35.     }
  36.     public void setPassword(String password) {
  37.         this.password = password;
  38.     }
  39.     public int getAge() {
  40.         return age;
  41.     }
  42.     public void setAge(int age) {
  43.         this.age = age;
  44.     }
  45.     public float getHeight() {
  46.         return height;
  47.     }
  48.     public void setHeight(float height) {
  49.         this.height = height;
  50.     }
  51.     public boolean isActive() {
  52.         return isActive;
  53.     }
  54.     public void setActive(boolean active) {
  55.         isActive = active;
  56.     }
  57.     public long getCreatedTime() {
  58.         return createdTime;
  59.     }
  60.     public void setCreatedTime(long createdTime) {
  61.         this.createdTime = createdTime;
  62.     }
  63.     // toString 方法
  64.     @Override
  65.     public String toString() {
  66.         return "User{" +
  67.                 "id=" + id +
  68.                 ", username='" + username + '\'' +
  69.                 ", age=" + age +
  70.                 ", height=" + height +
  71.                 ", isActive=" + isActive +
  72.                 ", createdTime=" + createdTime +
  73.                 '}';
  74.     }
  75. }
复制代码

三、使用Sqlite工具类(直接调用)

1.增

   DatabaseHelper.getInstance(getApplicationContext()).insertUser("zs","1",18,12,true);
  2.删

   DatabaseHelper.getInstance(getApplicationContext()).deleteUser(1);
  3.改

   DatabaseHelper.getInstance(getApplicationContext()).updateUser(4,"zs44","1",18,12,true);
  4.查

   //查询所有用户
  List<UserBean> userList = new ArrayList<>();
userList = DatabaseHelper.getInstance(getApplicationContext()).getAllUsers();
for(UserBean cell : userList){
    Log.d("test",cell.toString());
}
  
  //查询指定用户
  UserBean user;
user = DatabaseHelper.getInstance(getApplicationContext()).getUserById(1);
Log.d("test",user.toString());
  


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4