第四十八篇--数据库的增删改查

 

数据库的操作有两种方式,一种是使用内部API,一种是使用SQL语言。

方法一:

首先,设置布局文件

activity_main.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <android.support.constraint.ConstraintLayout 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     tools:context=".MainActivity">
 8 
 9     <EditText
10         android:id="@+id/et_name"
11         android:layout_width="wrap_content"
12         android:layout_height="wrap_content"
13         android:layout_marginStart="8dp"
14         android:layout_marginTop="40dp"
15         android:layout_marginEnd="8dp"
16         android:ems="10"
17         android:hint="姓名"
18         android:inputType="textPersonName"
19         app:layout_constraintEnd_toEndOf="parent"
20         app:layout_constraintHorizontal_bias="0.503"
21         app:layout_constraintStart_toStartOf="parent"
22         app:layout_constraintTop_toTopOf="parent" />
23 
24     <EditText
25         android:id="@+id/et_phone"
26         android:layout_width="wrap_content"
27         android:layout_height="wrap_content"
28         android:layout_marginStart="8dp"
29         android:layout_marginTop="28dp"
30         android:layout_marginEnd="8dp"
31         android:ems="10"
32         android:hint="请输入电话号码"
33         android:inputType="phone"
34         app:layout_constraintEnd_toEndOf="parent"
35         app:layout_constraintHorizontal_bias="0.503"
36         app:layout_constraintStart_toStartOf="parent"
37         app:layout_constraintTop_toBottomOf="@+id/et_name" />
38 
39     <Button
40         android:id="@+id/button"
41         android:layout_width="85dp"
42         android:layout_height="wrap_content"
43         android:layout_marginStart="8dp"
44         android:layout_marginTop="60dp"
45         android:layout_marginEnd="8dp"
46         android:onClick="add"
47         android:text=""
48         app:layout_constraintEnd_toEndOf="parent"
49         app:layout_constraintHorizontal_bias="0.501"
50         app:layout_constraintStart_toStartOf="parent"
51         app:layout_constraintTop_toBottomOf="@+id/et_phone" />
52 
53     <Button
54         android:id="@+id/button2"
55         android:layout_width="wrap_content"
56         android:layout_height="wrap_content"
57         android:layout_marginStart="8dp"
58         android:layout_marginTop="16dp"
59         android:layout_marginEnd="8dp"
60         android:onClick="delete"
61         android:text=""
62         app:layout_constraintEnd_toEndOf="parent"
63         app:layout_constraintStart_toStartOf="parent"
64         app:layout_constraintTop_toBottomOf="@+id/button" />
65 
66     <Button
67         android:id="@+id/button3"
68         android:layout_width="wrap_content"
69         android:layout_height="wrap_content"
70         android:layout_marginStart="8dp"
71         android:layout_marginTop="16dp"
72         android:layout_marginEnd="8dp"
73         android:onClick="update"
74         android:text=""
75         app:layout_constraintEnd_toEndOf="parent"
76         app:layout_constraintStart_toStartOf="parent"
77         app:layout_constraintTop_toBottomOf="@+id/button2" />
78 
79     <Button
80         android:id="@+id/button4"
81         android:layout_width="wrap_content"
82         android:layout_height="wrap_content"
83         android:layout_marginStart="8dp"
84         android:layout_marginTop="16dp"
85         android:layout_marginEnd="8dp"
86         android:onClick="query"
87         android:text=""
88         app:layout_constraintEnd_toEndOf="parent"
89         app:layout_constraintStart_toStartOf="parent"
90         app:layout_constraintTop_toBottomOf="@+id/button3" />
91 </android.support.constraint.ConstraintLayout>
View Code

然后写一个数据库创建和更新的文件

MyDBOpenHelper.java

 1 package com.aimee.android.play.createdb3;
 2 
 3 import android.content.Context;
 4 import android.database.sqlite.SQLiteDatabase;
 5 import android.database.sqlite.SQLiteOpenHelper;
 6 import android.util.Log;
 7 
 8 public class MyDBOpenHelper extends SQLiteOpenHelper {
 9     private static final String TAG = "MainActivity";
10     /**
11      * 第一个参数是上下文
12      * 第二个参数是数据库名称
13      * 第三个参数null表示使用默认的游标广场
14      * 第四个参数是数据库的版本号,数据库只能升级,不能降级,版本号只能增大不能变小
15      * @param context
16      */
17     public MyDBOpenHelper(Context context) {
18         super(context, "glsite", null, 1);
19     }
20 
21     /**
22      * 当数据库第一次被创建的时候调用的方法,适合在这个方法中把数据库的表结构定义出来
23      * @param db
24      */
25     @Override
26     public void onCreate(SQLiteDatabase db) {
27         Log.i(TAG,"onCreate 数据库被创建了");
28         db.execSQL("create table contactinfo(\n" +
29                 "id integer primary key autoincrement,\n" +
30                 "name char(20),\n" +
31                 "phone varchar(20)\n" +
32                 ")\n");
33     }
34 
35     /**
36      * 当数据库更新的时候调用的方法
37      * @param db
38      *           数据库对象
39      * @param oldVersion
40      *          老版本
41      * @param newVersion
42      *          新版本
43      */
44     @Override
45     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
46         Log.i(TAG,"数据库被更新了");
47         db.execSQL("alter table contactinfo add accout varchar(20);");
48     }
49 }
View Code

接着,创建数据库之后,对数据进行增删改查,新建一个class,放在Dao文件夹下

ContactInfoDao.java

 1 package com.aimee.android.play.createdb3.dao;
 2 
 3 import android.content.ContentValues;
 4 import android.content.Context;
 5 import android.database.Cursor;
 6 import android.database.sqlite.SQLiteDatabase;
 7 
 8 import com.aimee.android.play.createdb3.MyDBOpenHelper;
 9 
10 public class ContactInfoDao {
11     private final MyDBOpenHelper helper;
12     public ContactInfoDao(Context context){
13         helper = new MyDBOpenHelper(context);
14     }
15 
16     /**
17      * 添加一条数据
18      * @param name
19      *          联系人姓名
20      * @param phone
21      *          联系人电话
22      */
23     public void add(String name, String phone){
24         SQLiteDatabase db = helper.getWritableDatabase();
25         ContentValues values = new ContentValues();
26         values.put("name",name);
27         values.put("phone",phone);
28         db.insert("contactinfo",null,values);
29         //记得关闭数据库释放资源
30         db.close();
31     }
32 
33     /**
34      * 删除一条数据
35      * @param name
36      *          联系人姓名
37      */
38     public void delete(String name){
39         SQLiteDatabase db = helper.getWritableDatabase();
40         db.delete("contactinfo","name=?",new String[]{name});
41         //记得关闭数据库释放资源
42         db.close();
43     }
44 
45     /**
46      * 修改联系人电话号码
47      * @param name
48      *          联系人姓名
49      * @param phone
50      *          联系人电话
51      */
52     public void update(String name, String phone){
53         SQLiteDatabase db = helper.getWritableDatabase();
54         ContentValues values = new ContentValues();
55         values.put("phone",phone);
56         db.update("contactinfo",values,"name=?",new String[]{name});
57         //记得关闭数据库释放资源
58         db.close();
59     }
60 
61     /**
62      * 查询联系人电话号码
63      * @param name
64      *          联系人姓名
65      * @return phone
66      *           联系人电话
67      */
68     public String query(String name){
69         SQLiteDatabase db = helper.getWritableDatabase();
70         Cursor cursor = db.query("contactinfo", new String[]{"phone"},"name=?",
71                 new String[]{name},null,null,null);
72         String phone = null;
73         if (cursor.moveToNext()){
74             phone = cursor.getString(0);
75         }
76         cursor.close();
77 
78         //记得关闭数据库释放资源
79         db.close();
80         return phone;
81     }
82 }
View Code

最后,在主文件进行调用

MainActivity.java

 1 package com.aimee.android.play.createdb3;
 2 
 3 import android.support.v7.app.AppCompatActivity;
 4 import android.os.Bundle;
 5 import android.text.TextUtils;
 6 import android.view.View;
 7 import android.widget.EditText;
 8 import android.widget.Toast;
 9 
10 import com.aimee.android.play.createdb3.dao.ContactInfoDao;
11 
12 public class MainActivity extends AppCompatActivity {
13 
14     private static final String TAG = "MainActivity";
15     private EditText mEtName;
16     private EditText mEtPhone;
17     private ContactInfoDao mDao;
18 
19     @Override
20     protected void onCreate(Bundle savedInstanceState) {
21         super.onCreate(savedInstanceState);
22         setContentView(R.layout.activity_main);
23         //1.找到需要用到的控件
24         mEtName = findViewById(R.id.et_name);
25         mEtPhone = findViewById(R.id.et_phone);
26         //2.new一个Dao对象出来
27         mDao = new ContactInfoDao(this);
28 
29 //        MyDBOpenHelper helper = new MyDBOpenHelper(this);
30 //        helper.getWritableDatabase();
31     }
32 
33     /**
34      * 添加一条联系人信息
35      * @param view
36      */
37     public void add(View view){
38         String name = mEtName.getText().toString().trim();
39         String phone = mEtPhone.getText().toString().trim();
40 
41         if (TextUtils.isEmpty(name) || TextUtils.isEmpty(phone)){
42             Toast.makeText(this,"不能为空",Toast.LENGTH_SHORT).show();
43         }else {
44             mDao.add(name,phone);
45             Toast.makeText(this,"添加",Toast.LENGTH_SHORT).show();
46         }
47     }
48 
49     /**
50      * 删除一条联系人信息
51      * @param view
52      */
53     public void delete(View view){
54         String name = mEtName.getText().toString().trim();
55 
56         if (TextUtils.isEmpty(name)){
57             Toast.makeText(this,"不能为空",Toast.LENGTH_SHORT).show();
58         }else {
59             mDao.delete(name);
60             Toast.makeText(this,"删除",Toast.LENGTH_SHORT).show();
61         }
62     }
63 
64     /**
65      * 修改一条联系人信息
66      * @param view
67      */
68     public void update(View view){
69         String name = mEtName.getText().toString().trim();
70         String phone = mEtPhone.getText().toString().trim();
71 
72         if (TextUtils.isEmpty(name) || TextUtils.isEmpty(phone)){
73             Toast.makeText(this,"不能为空",Toast.LENGTH_SHORT).show();
74         }else {
75             mDao.update(name,phone);
76             Toast.makeText(this,"修改",Toast.LENGTH_SHORT).show();
77         }
78     }
79 
80     /**
81      * 查询一条联系人信息
82      * @param view
83      */
84     public void query(View view){
85         String name = mEtName.getText().toString().trim();
86 
87         if (TextUtils.isEmpty(name)){
88             Toast.makeText(this,"不能为空",Toast.LENGTH_SHORT).show();
89         }else {
90             String phone = mDao.query(name);
91             Toast.makeText(this,"查询到的号码为"+phone,Toast.LENGTH_SHORT).show();
92         }
93     }
94 }
View Code

效果图:

 方法二:

只需要在方法一的基础上,修改一个文件就好

ContactInfoDao.java

package com.aimee.android.play.createdb2.dao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.aimee.android.play.createdb2.MyDBOpenHelper;

public class ContactInfoDao {
    private final MyDBOpenHelper helper;
    public ContactInfoDao(Context context){
        helper = new MyDBOpenHelper(context);
    }

    /**
     * 添加一条数据
     * @param name
     *          联系人姓名
     * @param phone
     *          联系人电话
     */
    public void add(String name, String phone){
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL("insert into contactinfo(name,phone) values(?,?)",new Object[]{name,phone});

        //记得关闭数据库释放资源
        db.close();
    }

    /**
     * 删除一条数据
     * @param name
     *          联系人姓名
     */
    public void delete(String name){
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL("delete from contactinfo where name = ?;",new Object[]{name});

        //记得关闭数据库释放资源
        db.close();
    }

    /**
     * 修改联系人电话号码
     * @param name
     *          联系人姓名
     * @param phone
     *          联系人电话
     */
    public void update(String name, String phone){
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL("update contactinfo set phone = ? where name = ?;",new Object[]{phone,name});

        //记得关闭数据库释放资源
        db.close();
    }

    /**
     * 查询联系人电话号码
     * @param name
     *          联系人姓名
     * @return phone
     *           联系人电话
     */
    public String query(String name){
        SQLiteDatabase db = helper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select phone from contactinfo where name = ?;", new String[]{name});
        String phone = null;
        if (cursor.moveToNext()){
            phone = cursor.getString(0);
        }
        cursor.close();

        //记得关闭数据库释放资源
        db.close();
        return phone;
    }
}
View Code

 

posted @ 2019-05-07 16:23  o云淡风轻o  阅读(262)  评论(0编辑  收藏  举报