安卓开发数据库的简单操作

数据库帮助器SQLitOpenHelper

操作步骤:

  1. 新建一个继承自SQLiteOpenHelper的数据库操作类,重写onCreate()方法和onUpgrage()方法
  2. 封装保证数据安全的必要方法
  3. 提供对表记录增删改查的操作方法

SQLiteOpenHelper的子类实现的方法

注:这里的构造方法是单例模式的构造方法,但是由于访问量不是很大,不需要进行单例模式的安全考虑

  1. 首先是构造方法,(调用父类的构造方法)

Super(context,name.null,1)

参数context上下文,name数据库名称,null表示可造的游标工厂,1表示版本号

  1. onCreate() 创建数据库表,执行创建语句

通过使用SQLiteDatabase中的execSQL()方法执行语句

  1. onUpgreage() 修改版本

参数有SQLiteDatabase对象,旧版本,新版本

  1. 打开数据库的连接

打开读连接

Private SQLiteDatabase sqlRead = null;//定义一个读对象

  1.  public SQLiteDatabase openDbRead() {
  2.         if (!sqRead.isOpen() || sqRead == null) {//判断之前是否有打开读操作
  3.             sqRead = userDbHelper.getReadableDatabase();
  4.         }
  5.         return sqRead;//直接返回
  6.     }

打开写连接

private SQLiteDatabase sqWRrite = null;

  1. public SQLiteDatabase openDbWrite() {
  2.         if (sqWrite == null || !sqWrite.isOpen()) {
  3.             sqWrite = userDbHelper.getWritableDatabase();
  4.         }
  5.         return sqWrite;
  6.     }

  1. 关闭数据库的连接

数据库关闭借助close()方法

  1. 增删改查的方法

ContentValues value = new ContentValues();//相当于一个map,将数据存储到这个map中,然后写到数据中

sqWrite.insert(表名,null,value);

将数据写到表中

创建数据表,实战

Java代码

这个是借助SQLiteOpenHelper子类实现数据库的创建

  1. package com.example.chapter6.database;
  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.SQLiteOpenHelper;
  7. import com.example.chapter6.utils.User;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. public class UserDbHelper extends SQLiteOpenHelper {
  11.     //定义数据库的名字
  12.     private final static String dbName = "user.db";
  13.     private final static int dbVersion = 1;
  14.     private final static String tableName = "user_info";
  15.     private static UserDbHelper userDbHelper = null;
  16.     //写操作
  17.     private SQLiteDatabase sqWrite = null;
  18.     //读操作
  19.     private SQLiteDatabase sqRead = null;
  20.     //构造方法,调用父类的构造方法
  21.     private UserDbHelper(Context context) {
  22.         super(context, dbName, null, dbVersion);
  23.     }
  24.     public static UserDbHelper createDatabase(Context context) {
  25.         //判断对象是否已经存在
  26.         if (userDbHelper == null) {
  27.             userDbHelper = new UserDbHelper(context);
  28.         }
  29.         //存在直接返回
  30.         return userDbHelper;
  31.     }
  32.     //打开数据库读连接
  33.     public SQLiteDatabase openDbRead() {
  34.         if (sqRead == null || !sqRead.isOpen()) {
  35.             sqRead = userDbHelper.getReadableDatabase();
  36.         }
  37.         return sqRead;
  38.     }
  39.     //打开数据库写连接
  40.     public SQLiteDatabase openDbWrite() {
  41.         if (sqWrite == null || !sqWrite.isOpen()) {
  42.             sqWrite = userDbHelper.getWritableDatabase();
  43.         }
  44.         return sqWrite;
  45.     }
  46.     //关闭数据库连接
  47.     public void closeLink() {
  48.         //关闭数据库读操作
  49.         if (sqRead != null && sqRead.isOpen()) {
  50.             sqRead.close();
  51.             sqRead = null;
  52.         }
  53.         //关闭数据库写操作
  54.         if (sqWrite != null && sqWrite.isOpen()){
  55.             sqWrite.close();
  56.             sqWrite = null;
  57.         }
  58.     }
  59.     //创建生成数据库的表
  60.     @Override
  61.     public void onCreate(SQLiteDatabase db) {
  62.         String sql = "CREATE TABLE IF NOT EXISTS " + tableName + "(" +
  63.                 "id INTEGER PRIMARY KEY AUTOINCREMENT," +
  64.                 "name VARCHAR NOT NULL," +
  65.                 "age INTEGER," +
  66.                 "height LONG," +
  67.                 "weight FLOAT," +
  68.                 "married INTEGER);";
  69.         db.execSQL(sql);
  70.     }
  71.     @Override
  72.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  73.     }
  74.     //增删改查的方法
  75.     //新增
  76.     public long insertSql(User user){
  77.         sqWrite = openDbWrite();
  78.        // sqRead = openDbRead();
  79.         ContentValues values = new ContentValues();
  80.         values.put("name",user.name);
  81.         values.put("age",user.age);
  82.         values.put("height",user.height);
  83.         values.put("weight",user.weight);
  84.         values.put("married",user.married);
  85.         return sqWrite.insert(tableName,null,values);//将数据写入数据库中
  86.     }
  87.     //删除
  88.     public long deleteSql(String name){
  89.       //  ContentValues values = new ContentValues();
  90.         //删除数据
  91.         return sqWrite.delete(tableName,"name=?",new String[]{name});
  92.     }
  93.     //修改
  94.     public long updateSql(User user){
  95.         ContentValues values = new ContentValues();
  96.         values.put("name",user.name);
  97.         values.put("age",user.age);
  98.         values.put("height",user.height);
  99.         values.put("weight",user.weight);
  100.         values.put("married",user.married);
  101.         return sqWrite.update(tableName,values,"name=?",new String[]{user.name});
  102.     }
  103.     //查询
  104.     public List<User> queryAll(){
  105.         List<User> list = new ArrayList<>();
  106.         Cursor query = sqRead.query(tableName, null, null, null, null, null, null);//查询拿到一个游标
  107.         while (query.moveToNext()){
  108.            User user = new User();
  109.            user.id = query.getInt(0);
  110.            user.name = query.getString(1);
  111.            user.age = query.getInt(2);
  112.            user.height = query.getLong(3);
  113.            user.weight = query.getFloat(4);
  114.            user.married = (query.getInt(5) == 0)?false:true;
  115.            list.add(user);
  116.         }
  117.         return list;
  118.     }
  119. }

以及工具类utils包中的user类

  1. package com.example.chapter6.utils;
  2. public class User {
  3.     public Integer id;
  4.     public String name;
  5.     public Integer age;
  6.     public long height;
  7.     public float weight;
  8.     public boolean married;
  9.     public User() {
  10.     }
  11.     public User(String name, Integer age, long height, float weight, boolean married) {
  12.         this.name = name;
  13.         this.age = age;
  14.         this.height = height;
  15.         this.weight = weight;
  16.         this.married = married;
  17.     }
  18.     @Override
  19.     public String toString() {
  20.         return "User{" +
  21.                 "id=" + id +
  22.                 ", name='" + name + '\'' +
  23.                 ", age=" + age +
  24.                 ", height=" + height +
  25.                 ", weight=" + weight +
  26.                 ", married=" + married +
  27.                 '}';
  28.     }
  29. }

这段代码是事件监听,activity中的代码

  1. package com.example.chapter6;
  2. import androidx.appcompat.app.AppCompatActivity;
  3. import android.database.sqlite.SQLiteDatabase;
  4. import android.os.Bundle;
  5. import android.os.UserHandle;
  6. import android.util.Log;
  7. import android.view.View;
  8. import android.widget.Button;
  9. import android.widget.CheckBox;
  10. import android.widget.EditText;
  11. import android.widget.Toast;
  12. import com.example.chapter6.database.UserDbHelper;
  13. import com.example.chapter6.utils.User;
  14. import java.util.List;
  15. public class OpenHelperActivity extends AppCompatActivity {
  16.     private EditText et_name;
  17.     private EditText et_age;
  18.     private EditText et_height;
  19.     private EditText et_weight;
  20.     private CheckBox ck_married;
  21.     private UserDbHelper database;
  22.     @Override
  23.     protected void onCreate(Bundle savedInstanceState) {
  24.         super.onCreate(savedInstanceState);
  25.         setContentView(R.layout.activity_openhelper);
  26.         addNumber();
  27.     }
  28.     //在这里打开数据库的读写
  29.     @Override
  30.     protected void onStart() {
  31.         super.onStart();
  32.         database = UserDbHelper.createDatabase(OpenHelperActivity.this);
  33.         database.openDbRead();
  34.         database.openDbWrite();
  35.     }
  36.     @Override
  37.     protected void onStop() {
  38.         super.onStop();
  39.         database.closeLink();//关闭数据库
  40.     }
  41.     public void addNumber(){
  42.         et_name = findViewById(R.id.et_name);
  43.         et_age = findViewById(R.id.et_age);
  44.         et_height = findViewById(R.id.et_height);
  45.         et_weight = findViewById(R.id.et_weight);
  46.         ck_married = findViewById(R.id.ck_married);
  47.         Button bt_insert = findViewById(R.id.bt_insert);
  48.         Button bt_delete = findViewById(R.id.bt_delete);
  49.         Button bt_update = findViewById(R.id.bt_update);
  50.         Button bt_query = findViewById(R.id.bt_query);
  51.         bt_insert.setOnClickListener(new View.OnClickListener() {
  52.             @Override
  53.             public void onClick(View v) {
  54.                 String name = et_name.getText().toString();
  55.                 String age = et_age.getText().toString();
  56.                 String height = et_height.getText().toString();
  57.                 String weight = et_weight.getText().toString();
  58.                 User user = new User(name,Integer.parseInt(age),Long.parseLong(height),Short.parseShort(weight),ck_married.isChecked());
  59.                 if (database.insertSql(user)>0){//如果大于0,表示添加成功
  60.                     Toast.makeText(OpenHelperActivity.this,"添加成功",Toast.LENGTH_SHORT).show();
  61.                 }
  62.             }
  63.         });
  64.         bt_update.setOnClickListener(new View.OnClickListener() {
  65.             @Override
  66.             public void onClick(View v) {
  67.                 String name = et_name.getText().toString();
  68.                 String age = et_age.getText().toString();
  69.                 String height = et_height.getText().toString();
  70.                 String weight = et_weight.getText().toString();
  71.                 User user = new User(name,Integer.parseInt(age),Long.parseLong(height),Short.parseShort(weight),ck_married.isChecked());
  72.                 database.updateSql(user);
  73.                 if (database.updateSql(user)>0){
  74.                     Toast.makeText(OpenHelperActivity.this,"修改成功",Toast.LENGTH_SHORT).show();
  75.                 }
  76.             }
  77.         });
  78.         bt_delete.setOnClickListener(new View.OnClickListener() {
  79.             @Override
  80.             public void onClick(View v) {
  81.                 String name = et_name.getText().toString();
  82.                 if(database.deleteSql(name)>0){
  83.                     Toast.makeText(OpenHelperActivity.this,"删除成功",Toast.LENGTH_SHORT).show();
  84.                 }
  85.             }
  86.         });
  87.         bt_query.setOnClickListener(new View.OnClickListener() {
  88.             @Override
  89.             public void onClick(View v) {
  90.                 List<User> list = database.queryAll();
  91.                 for(User u :list){
  92.                     Log.d("nin",u.toString());
  93.                 }
  94.             }
  95.         });
  96.     }
  97. }

以及xml配置文件,就是基础的页面布局

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"
  4.     xmlns:tools="http://schemas.android.com/tools"
  5.     android:layout_width="match_parent"
  6.     android:layout_height="match_parent"
  7.     android:orientation="vertical">
  8.     <LinearLayout
  9.         android:layout_width="match_parent"
  10.         android:layout_height="wrap_content"
  11.         android:layout_marginTop="10dp"
  12.         android:layout_marginBottom="10dp">
  13.         <TextView
  14.             android:layout_width="wrap_content"
  15.             android:layout_height="wrap_content"
  16.             android:background="@drawable/edit_selected"
  17.             android:padding="10dp"
  18.             android:text="姓名"
  19.             android:textSize="20sp" />
  20.         <EditText
  21.             android:id="@+id/et_name"
  22.             android:layout_width="0dp"
  23.             android:layout_height="match_parent"
  24.             android:layout_weight="1"
  25.             android:background="@drawable/edit_selected"
  26.             android:padding="5dp" />
  27.     </LinearLayout>
  28.     <LinearLayout
  29.         android:layout_width="match_parent"
  30.         android:layout_height="wrap_content"
  31.         android:layout_marginTop="5dp"
  32.         android:layout_marginBottom="5dp">
  33.         <TextView
  34.             android:layout_width="wrap_content"
  35.             android:layout_height="wrap_content"
  36.             android:background="@drawable/edit_selected"
  37.             android:padding="10dp"
  38.             android:text="年龄"
  39.             android:textSize="20sp" />
  40.         <EditText
  41.             android:id="@+id/et_age"
  42.             android:layout_width="0dp"
  43.             android:layout_height="match_parent"
  44.             android:layout_weight="1"
  45.             android:background="@drawable/edit_selected"
  46.             android:padding="5dp" />
  47.     </LinearLayout>
  48.     <LinearLayout
  49.         android:layout_width="match_parent"
  50.         android:layout_height="wrap_content"
  51.         android:layout_marginTop="5dp"
  52.         android:layout_marginBottom="5dp">
  53.         <TextView
  54.             android:layout_width="wrap_content"
  55.             android:layout_height="wrap_content"
  56.             android:background="@drawable/edit_selected"
  57.             android:padding="10dp"
  58.             android:text="身高"
  59.             android:textSize="20sp" />
  60.         <EditText
  61.             android:id="@+id/et_height"
  62.             android:layout_width="0dp"
  63.             android:layout_height="match_parent"
  64.             android:layout_weight="1"
  65.             android:background="@drawable/edit_selected"
  66.             android:padding="5dp" />
  67.     </LinearLayout>
  68.     <LinearLayout
  69.         android:layout_width="match_parent"
  70.         android:layout_height="wrap_content"
  71.         android:layout_marginTop="5dp"
  72.         android:layout_marginBottom="5dp">
  73.         <TextView
  74.             android:layout_width="wrap_content"
  75.             android:layout_height="wrap_content"
  76.             android:background="@drawable/edit_selected"
  77.             android:padding="10dp"
  78.             android:text="体重"
  79.             android:textSize="20sp" />
  80.         <EditText
  81.             android:id="@+id/et_weight"
  82.             android:layout_width="0dp"
  83.             android:layout_height="match_parent"
  84.             android:layout_weight="1"
  85.             android:background="@drawable/edit_selected"
  86.             android:padding="5dp" />
  87.     </LinearLayout>
  88.     <CheckBox
  89.         android:id="@+id/ck_married"
  90.         android:layout_width="match_parent"
  91.         android:layout_height="wrap_content"
  92.         android:layout_marginTop="5dp"
  93.         android:layout_marginBottom="5dp"
  94.         android:text="已婚"
  95.         android:textSize="15sp" />
  96.     <Button
  97.         android:id="@+id/bt_insert"
  98.         android:layout_width="match_parent"
  99.         android:layout_height="wrap_content"
  100.         android:layout_marginBottom="10dp"
  101.         android:background="@drawable/edit_selected"
  102.         android:text="新增"
  103.         android:textColor="#000000"
  104.         android:textSize="20sp" />
  105.     <Button
  106.         android:id="@+id/bt_update"
  107.         android:layout_width="match_parent"
  108.         android:layout_height="wrap_content"
  109.         android:background="@drawable/edit_selected"
  110.         android:text="修改"
  111.         android:layout_marginBottom="10dp"
  112.         android:textColor="#000000"
  113.         android:textSize="20sp" />
  114.     <Button
  115.         android:id="@+id/bt_delete"
  116.         android:layout_width="match_parent"
  117.         android:layout_height="wrap_content"
  118.         android:background="@drawable/edit_selected"
  119.         android:text="删除"
  120.         android:textColor="#000000"
  121.         android:layout_marginBottom="10dp"
  122.         android:textSize="20sp" />
  123.     <Button
  124.         android:id="@+id/bt_query"
  125.         android:layout_width="match_parent"
  126.         android:layout_height="wrap_content"
  127.         android:background="@drawable/edit_selected"
  128.         android:text="查询"
  129.         android:textColor="#000000"
  130.         android:textSize="20sp" />
  131. </LinearLayout>

增删改查的几个数据库操作

首先是查询

需要创建一个List<User> list = new ArrayList<>;将从数据库中查询的数据存储到这个集合中,通过游标进行查询

Cursor query = sqlRead.query(数据库表名,null,null,...);

while(query.moveToNext){//判断是否有下一行

然后查询

Query.getInt(0);

根据顺序依次查询每行的数据

最终添加到list集合中

}

返回list集合

删除

删除比较简单,直接通过传入的查询条件

通过sqlWrite.delete(表名,”name=?”,new String[{name});直接将这个返回,在操作页面,判断这个参数是否大于0,大于零就证明操作成功

增加

首先借助ContentViews对象,这是一个map来存储对象信息

ContentViews view = new ContentViews();

通过view.put将数据存储

sqlWrite.insert(表名,null,views);

修改

首先借助ContentViews对象,这是一个map来存储需要修改对象的信息

ContentViews view = new ContentViews();

然后直接返回sqlWrite.update(表名,view,”name=?”,new String[]{user.name})

后面的增删改都是在写操作上进行,只有查询在读操作上进行的

事物管理,保持数据的一致性

BeginTransaction 开始事物

setTransactionSuccessful() 设置事物成功的标志,否则会回滚

EndTransaaction结束事物

  1. try {
  2.             sqWrite.beginTransaction();//开始事物
  3.             return sqWrite.insert(tableName,null,values);//将数据写入数据库中
  4.             sqWrite.setTransactionSuccessful();//设置事物成功标志,如果不设置,则回滚事物
  5.         }catch (Exception e){
  6.             e.printStackTrace();
  7.         }finally {
  8.             sqWrite.endTransaction();//结束事物
  9.         }

  • 30
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值