zoukankan      html  css  js  c++  java
  • Android之SQLite数据库操作

    设计一个简单的学生信息管理程序,数据库名称创建为”ciec”,学生信息包括学号(表的主键)、姓名、性别、班级等,结合SQLite数据库实现对学生信息的添加、修改、删除与查询操作。

    实验步骤

    创建一个Activity,界面布局如图1所示,用户通过界面输入或选择学生信息,点击添加按钮后,将信息保存到数据库中,并在界面中提示操作成功或失败的信息。注意:输入的学号为数据库表的主键,学号不能为空也不能重复,需要在程序中对学号的信息进行合法性验证。

    点击修改按钮和删除按钮可以对学生信息进行相应操作,但必须预先输入学号信息,否则提示操作无法成功。

    点击查询按钮后,先跳转到新的Activity,在新的界面中展示查询结果,要求将所有的学生信息都查询出来,并用列表控件进行展示,界面布局如图2所示。

                           图1                                                            图2

    写了一天才写完,一开始写的时候一脸懵

    说一下总共写了6个文件,Mainactivity,Secondactivity,DatabaseHelper,还有三个xml布局文件

    先把布局文件贴出来

      1 <?xml version="1.0" encoding="utf-8"?>
      2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      3     android:layout_width="match_parent"
      4     android:layout_height="match_parent"
      5     android:orientation="vertical">
      6 
      7     <LinearLayout
      8         android:layout_width="match_parent"
      9         android:layout_height="50dp"
     10         android:orientation="horizontal">
     11 
     12         <TextView
     13             android:layout_width="match_parent"
     14             android:layout_height="match_parent"
     15             android:layout_weight="3"
     16             android:text=" 学号 : "/>
     17         <EditText
     18             android:id="@+id/Stdudent_ID"
     19             android:layout_width="match_parent"
     20             android:layout_height="match_parent"
     21             android:layout_weight="1" />
     22     </LinearLayout>
     23 
     24     <LinearLayout
     25         android:layout_width="match_parent"
     26         android:layout_height="50dp"
     27         android:orientation="horizontal">
     28 
     29         <TextView
     30             android:layout_width="match_parent"
     31             android:layout_height="match_parent"
     32             android:layout_weight="3"
     33             android:text=" 姓名 : "/>
     34         <EditText
     35             android:id="@+id/Stdudent_NAME"
     36             android:layout_width="match_parent"
     37             android:layout_height="match_parent"
     38             android:layout_weight="1" />
     39     </LinearLayout>
     40 
     41     <LinearLayout
     42         android:layout_width="match_parent"
     43         android:layout_height="50dp"
     44         android:orientation="horizontal">
     45 
     46         <TextView
     47             android:layout_width="102dp"
     48             android:layout_height="match_parent"
     49             android:text="性别" />
     50 
     51         <RadioGroup
     52             android:id="@+id/Student_SEX"
     53             android:layout_width="wrap_content"
     54             android:layout_height="wrap_content"
     55             android:orientation="horizontal" >
     56 
     57             <RadioButton
     58                 android:id="@+id/Student_BOY"
     59                 android:layout_width="118dp"
     60                 android:layout_height="match_parent"
     61                 android:text="男" />
     62 
     63             <RadioButton
     64                 android:id="@+id/Student_GIRL"
     65                 android:layout_width="110dp"
     66                 android:layout_height="match_parent"
     67                 android:text="女" />
     68         </RadioGroup>
     69     </LinearLayout>
     70 
     71     <LinearLayout
     72         android:layout_width="match_parent"
     73         android:layout_height="50dp"
     74         android:orientation="horizontal">
     75 
     76         <TextView
     77             android:layout_width="match_parent"
     78             android:layout_height="match_parent"
     79             android:layout_weight="3"
     80             android:text=" 班级 : "/>
     81         <EditText
     82             android:id="@+id/Student_CLASS"
     83             android:layout_width="match_parent"
     84             android:layout_height="match_parent"
     85             android:layout_weight="1" />
     86     </LinearLayout>
     87 
     88     <LinearLayout
     89         android:layout_width="match_parent"
     90         android:layout_height="50dp"
     91         android:orientation="horizontal">
     92 
     93         <Button
     94             android:id="@+id/Stdudent_ADD"
     95             android:layout_width="match_parent"
     96             android:layout_height="wrap_content"
     97             android:layout_weight="1"
     98             android:text="添加" />
     99         <Button
    100             android:id="@+id/Stdudent_MV"
    101             android:layout_width="match_parent"
    102             android:layout_height="wrap_content"
    103             android:layout_weight="1"
    104             android:text="修改" />
    105         <Button
    106             android:id="@+id/Stdudent_RM"
    107             android:layout_width="match_parent"
    108             android:layout_height="wrap_content"
    109             android:layout_weight="1"
    110             android:text="删除" />
    111         <Button
    112             android:id="@+id/Stdudent_FIND"
    113             android:layout_width="match_parent"
    114             android:layout_height="wrap_content"
    115             android:layout_weight="1"
    116             android:text="查询" />
    117     </LinearLayout>
    118 
    119 </LinearLayout>
     1 <?xml version="1.0" encoding="utf-8"?>
     2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     3     android:layout_width="match_parent"
     4     android:layout_height="match_parent">
     5 
     6     <ListView
     7         android:id="@+id/Student_ALL"
     8         android:layout_height="fill_parent"
     9         android:layout_width="fill_parent"/>
    10 
    11 </LinearLayout>
     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     android:layout_width="match_parent"
     5     android:layout_height="match_parent">
     6 
     7     <TextView
     8         android:id="@+id/tv"
     9         android:layout_width="match_parent"
    10         android:layout_height="match_parent"/>
    11 
    12 </LinearLayout>

    这三个xml,第一个对应Mainactivity,后两个对应Secondactivity。

    第一次使用SQLlite,就先使用一下

     

     

     熟悉用法了,就可以开始写了

    sqllite数据库是AndroidSDK自带的,所以我们写一个类继承SQLiteOpenHelper类(这是个抽象类),而且需要在这个类中实现三个方法:构造函数,onCreate,onUpgrade

     1 package com.example.app;
     2 
     3 import android.annotation.SuppressLint;
     4 import android.content.Context;
     5 import android.database.Cursor;
     6 import android.database.sqlite.*;
     7 
     8 public class DatabaseHelper extends SQLiteOpenHelper { //带全部参数的构造函数,name为数据库名称
     9     public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,int version){
    10         super(context,name,factory,version);
    11     }
    12 
    13     @Override
    14     public void onCreate(SQLiteDatabase db) {  //建表
    15         db.execSQL("CREATE TABLE information(
    " +
    16                 "             id INTEGER PRIMARY KEY NOT NULL,
    " +
    17                 "             name TEXT NOT NULL,
    " +
    18                 "             sex TEXT NOT NULL,
    " +
    19                 "             class TEXT NOT NULL
    " +
    20                 "             )");
    21         db.execSQL("INSERT into information(id,name,sex,class) VALUES (202001,"张三","男","嵌入式1班");");
    22         db.execSQL("INSERT into information(id,name,sex,class) VALUES (202002,"王乐","男","嵌入式1班");");
    23         db.execSQL("INSERT into information(id,name,sex,class) VALUES (202003,"刘小慧","女","网编1班");");
    24     }
    25 
    26     @Override
    27     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//简单demo,就不写这个了
    28 
    29     }
    30     //只有conCreate()和onUpgrade是抽象方法,所以重写,
    31 
    32 }

    然后写Mainactivity,思路就是点击相对应的按钮做出相对应的操作

    package com.example.app;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.annotation.SuppressLint;
    import android.content.ContentValues;
    import android.content.Intent;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.*;
    
    public class MainActivity extends AppCompatActivity {
    
        private EditText Student_ID;
        private EditText Student_NAME;
        private EditText Student_CLASS;
        private RadioGroup Student_SEX;
        private RadioButton Student_BOY;
        private RadioButton Student_GIRL;
        private Button Stdudent_ADD;
        private Button Stdudent_MV;
        private Button Stdudent_RM;
        private Button Stdudent_FIND;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.homework_9_1);
    
            //5.
            //4.因为我们都在mainactivity上操作,所以就不提前在sqllit上建库了,直接在这个建库,开始运行时就把库先建好
            final DatabaseHelper databaseHelper = new DatabaseHelper(this,"ciec.db",null,2);
            SQLiteDatabase db = databaseHelper.getWritableDatabase(); // 这里先用.getreadableDatebase查一下
            //databaseHelper.exitDataBase(db);
    
            //1.对学号姓名班级进行实例化
            Student_ID = (EditText) findViewById(R.id.Stdudent_ID);
            Student_NAME = (EditText) findViewById(R.id.Stdudent_NAME);
            Student_CLASS = (EditText) findViewById(R.id.Student_CLASS);
            //2.实例化和监听性别选项
            Student_SEX = (RadioGroup) findViewById(R.id.Student_SEX);
            Student_BOY = (RadioButton) findViewById(R.id.Student_BOY);
            Student_GIRL = (RadioButton) findViewById(R.id.Student_GIRL);
    
            //Student_SEX.setOnCheckedChangeListener(new MyRadioButtonListener());
            //10.应该在点击按钮的时候获取这个单选的值
    
            //6.获取输入框的内容
    //        final String id = Student_ID.getText().toString().trim();
    //        final String name = Student_NAME.getText().toString().trim();
    //        final String classes = Student_CLASS.getText().toString().trim();
    
            //3.然后写增删改查功能
            Stdudent_ADD = (Button) findViewById(R.id.Stdudent_ADD);//增
            Stdudent_ADD.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final String id = Student_ID.getText().toString().trim();
                    final String name = Student_NAME.getText().toString().trim();
                    final String classes = Student_CLASS.getText().toString().trim();
                    String sex = "0";
                    if (Student_GIRL.isChecked()){
                        sex = "女";
                    }
                    if(Student_BOY.isChecked()){
                        sex = "男";
                    }
                    //8.我们设置的是学号姓名班级和性别都不能为空,所以进行判断
                    if (id.isEmpty() | name.isEmpty() | classes.isEmpty() | sex.equals("0")){//为null,则弹出提示框   使用isempty方法代替equals
                        Toast.makeText(MainActivity.this,"请将信息全部填完!!!",Toast.LENGTH_SHORT).show();
                    }else{
                        //7.将输入的内容插入数据库
                        //9.因为学号唯一,所以我们还得判断数据库中是否已经存在,如果存在则肯定不能插入了,否则和修改没啥区别了
                        SQLiteDatabase db = databaseHelper.getWritableDatabase();  //获得写入模式的数据库
                        ContentValues values = new ContentValues();
                        //db.execSQL("select _id from information where _id = "+ id +";");
                        Cursor cursor = db.query("information", new String[]{"id"},"id = ?", new String[] {id}, null, null, null);
                        if(cursor.getCount()>0){
                            Toast.makeText(MainActivity.this,"学生信息已经存在!!!",Toast.LENGTH_SHORT).show();
                        }else {
                            values.put("id",id);
                            values.put("name",name);
                            values.put("sex", sex);
                            values.put("class",classes);
                            db.insert("information",null,values);
                            Toast.makeText(MainActivity.this,"增加成功!!!",Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });
    
            Stdudent_MV = (Button) findViewById(R.id.Stdudent_MV);//改
            Stdudent_MV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final String id = Student_ID.getText().toString().trim();
                    final String name = Student_NAME.getText().toString().trim();
                    final String classes = Student_CLASS.getText().toString().trim();
                    String sex = "0";
                    if (Student_GIRL.isChecked()){
                        sex = "女";
                    }
                    if(Student_BOY.isChecked()){
                        sex = "男";
                    }
                    //修改必须有学号,所以点击修改按钮时就会覆盖相对应的学号的其他的值,
                    //就是说学号必须有,如果学号对应的账号信息被删除,则应该提示无此学生信息
                    if (id.isEmpty()){
                        Toast.makeText(MainActivity.this,"学号不能为空!!!",Toast.LENGTH_SHORT).show();
                    }else {
                        SQLiteDatabase db = databaseHelper.getWritableDatabase();
                        ContentValues values2 = new ContentValues();
                        ContentValues values3 = new ContentValues();
                        ContentValues values4 = new ContentValues();
                        Cursor cursor = db.query("information", new String[]{"id"},"id = ?", new String[] {id}, null, null, null);
                        if (cursor.getCount()>0){
                            values2.put("name",name);
                            values3.put("sex", sex);
                            values4.put("class",classes);
                            db.update("information",values2,"id = ?",new String[]{id});
                            db.update("information",values3,"id = ?",new String[]{id});
                            db.update("information",values4,"id = ?",new String[]{id});
                            Toast.makeText(MainActivity.this,"修改成功!!!",Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(MainActivity.this,"无此学生!!!",Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });
    
            Stdudent_RM = (Button) findViewById(R.id.Stdudent_RM);//删
            Stdudent_RM.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final String id = Student_ID.getText().toString().trim();
                    final String name = Student_NAME.getText().toString().trim();
                    final String classes = Student_CLASS.getText().toString().trim();
                    //删除只需要有学号就可以
                    if(id.equals("")){
                        Toast.makeText(MainActivity.this,"学号不能为空!!!",Toast.LENGTH_SHORT).show();
                    }else {
                        SQLiteDatabase db = databaseHelper.getWritableDatabase();
                        db.delete("information","id=?",new String[]{id});
                        Toast.makeText(MainActivity.this,"删除成功!!!",Toast.LENGTH_SHORT).show();
                    }
                }
            });
    
            Stdudent_FIND = (Button) findViewById(R.id.Stdudent_FIND);//查
            Stdudent_FIND.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //这里跳转到另一个activity
                    startActivity(new Intent(MainActivity.this,SecondActivity.class));
                }
            });
        }
    //    static class MyRadioButtonListener implements RadioGroup.OnCheckedChangeListener { //单选的类
    //        @Override
    //        public void onCheckedChanged(RadioGroup group, int checkedId) {
    //            String sex;
    //            // 选中状态改变时被触发
    //            switch (checkedId) {
    //                case R.id.Student_GIRL:
    //                    // 当用户选择女性时
    //                    sex = "女";
    //                    break;
    //                case R.id.Student_BOY:
    //                    // 当用户选择男性时
    //                    sex = "男";
    //                    break;
    //            }
    //        }
    //    }
    
    
    }
    

    然后写Secondactivity

    没啥好说的,就是查询,然后将数据展示出来

    这里说一个知识点

     

     

     1 package com.example.app;
     2 
     3 import androidx.appcompat.app.AppCompatActivity;
     4 import androidx.appcompat.app.AlertDialog;
     5 
     6 import android.database.Cursor;
     7 import android.database.sqlite.SQLiteDatabase;
     8 import android.text.TextUtils;
     9 
    10 import android.os.Bundle;
    11 import android.view.LayoutInflater;
    12 import android.view.View;
    13 import android.view.ViewGroup;
    14 import android.widget.ArrayAdapter;
    15 import android.widget.BaseAdapter;
    16 import android.widget.ListView;
    17 import android.widget.TextView;
    18 
    19 import java.util.ArrayList;
    20 
    21 public class SecondActivity extends AppCompatActivity {
    22 
    23     private ListView Student_ALL;
    24     String[] data;
    25     ArrayList<String> stringArrayList = new ArrayList<String>();
    26 
    27     @Override
    28     protected void onCreate(Bundle savedInstanceState) {
    29         super.onCreate(savedInstanceState);
    30         setContentView(R.layout.homework_9_2);
    31         final DatabaseHelper databaseHelper = new DatabaseHelper(this,"ciec.db",null,2);
    32 
    33         Student_ALL = (ListView) findViewById(R.id.Student_ALL);
    34 
    35         SQLiteDatabase db = databaseHelper.getWritableDatabase();
    36         Cursor cursor = db.query("information", new String[]{"id","name","sex","class"}, null, null, null, null, null);
    37         String textview_data = "";
    38         //利用游标遍历所有数据对象
    39         //为了显示全部,把所有对象连接起来,放到TextView中
    40         while(cursor.moveToNext()){
    41             String qwe = cursor.getString(cursor.getColumnIndex("id"));
    42             String asd = cursor.getString(cursor.getColumnIndex("name"));
    43             String zxc = cursor.getString(cursor.getColumnIndex("sex"));
    44             String qaz = cursor.getString(cursor.getColumnIndex("class"));
    45             textview_data = qwe + "--" + asd +"--" + zxc +"--" + qaz;
    46             stringArrayList.add(textview_data);
    47         }
    48         //利用arraylist,保存数据,然后在转换成String[]数组
    49         String [] stringArray = stringArrayList.toArray(new String[stringArrayList.size()]);
    50         data = stringArray;
    51         //多余的一行注释掉ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,R.id.LS);//新建并配置ArrayAapeter
    52         MyBaseAdapter mAdapter = new MyBaseAdapter();
    53         Student_ALL.setAdapter(mAdapter);
    54     }
    55 
    56     class MyBaseAdapter extends BaseAdapter {
    57 
    58         @Override
    59         public int getCount() {
    60             return data.length;
    61         }
    62         @Override
    63         public Object getItem(int position) {
    64             return null;
    65         }
    66         @Override
    67         public long getItemId(int position) {
    68             return 0;
    69         }
    70         @Override
    71         public View getView(int position, View convertView, ViewGroup parent) {
    72             ViewHolder holder;
    73             if(convertView == null){
    74                 convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.homework_five_2,parent,false);
    75                 holder = new ViewHolder();
    76                 holder.mTextView = (TextView) convertView.findViewById(R.id.tv);
    77                 convertView.setTag(holder);
    78             }else {
    79                 holder = (ViewHolder) convertView.getTag();
    80             }
    81             holder.mTextView.setText(data[position]);
    82             return convertView;
    83         }
    84         class ViewHolder {
    85             TextView mTextView;
    86         }
    87     }
    88 }

    最后的成品:

     

    到了总结的时候啦!

    插入数据:

    首先需要new一个ContentValues,内容值对象。
    所谓的内容值,就是一个K,V 键值对,K指明字段名称即列名称,V指明字段值,即单元格内容。然后将这个键值对放到ContentValues的对象values里面,再把携带着键值对的对象values插入user表中
    1 ContentValues values = new ContentValues();
    2 values.put("id",id);
    3 db.insert("information",null,values);

    删除数据:

    db.delete("information","id=?",new String[]{id});

    第一个参数是表名,第二个参数是删除条件,第三个参数就是你要删除的值,简单理解就是它会赋值给第二个参数的问号。

    修改数据:

    和插入数据相似,.update中的第一个参数是表名,第二个参数就是我们要修改的列名和值,第三个参数是修改条件,第四个参数是修改条件的值

    1 ContentValues values2 = new ContentValues();
    2 values2.put("name",name);
    3 db.update("information",values2,"id = ?",new String[]{id});

    查询数据:

    频繁的用到查询语句,然后查询语句也是我花时间最长的

    Cursor cursor = db.query("information", new String[]{"id"},"id = ?", new String[] {id}, null, null, null);

    这句写在插入功能,使用了Cursor游标进行查询,后面的循环遍历所有数据就不说了,单说一下这条语句

    cursor就是游标对象,查询函数是.query,第一个参数是表名,第二个参数就是select * from 表名 where name = “”;中的*号,第三个参数就是查询条件(where后跟的name = ),第四个参数是查询条件的值,再往后的几个参数就是各种查询约束了,在上面的查询知识点说的很清楚。

    还有一种查询函数是.rawQuery,这种查询方式是这样的

    .rawQuery(sql,selectionArgs)

    第一个参数是sql语句,第二个参数要么是null,要么必须是一个字符串数组,还有第三个参数,没用过不知道是啥

    比如这样

    Cursor cursor = db.rawQuery("select name from * where id=?", new String[]{"1"});

    这两个函数的主要区别是rawQuery是直接使用SQL语句进行查询的,也就是第一个参数字符串,在字符串内的“?”会被后面的String[]数组逐一对换掉;而query函数是Android自己封装的查询API

     

    写代码的时候有好多问题要总结的,结果写博客的时候发现都忘光了,不知道该写什么,哭

    补一张图:

     

     

    加油,未来可期!

  • 相关阅读:
    vue---echarts图表
    路由嵌套
    VoIP语音通话研究【进阶篇(四):freeswitch+webrtc+sip.js的通话】
    VoIP语音通话研究【进阶篇(三):opensips安装】
    如何在北京退休?
    后端分析/前端分析/边缘分析
    使用curl批量下载图片
    pytorch固定随机种子复现实验结果
    分享一个作为面试官的面试思路
    两个流程链路问题的排查和总结
  • 原文地址:https://www.cnblogs.com/rebirther/p/12924783.html
Copyright © 2011-2022 走看看