Android安卓——数据存储之数据库存储

来源:互联网 发布:商品抢购软件 编辑:程序博客网 时间:2024/06/05 15:31

在安卓开发中,对于用户端数据的存储常使用SQLite数据库。通常使用SQLite数据库在安卓开发中进行数据的增删查改操作。
本次讲解将会先介绍SQLite数据库,在读者对该数据库有了一定的了解之后,展开在安卓应用中对SQLite的使用。

一、SQLite数据库

1、SQLite数据库简介
(1)、SQLite数据库是一个开源的嵌入式关系数据库
(2)、特点:


  • 更加适用于嵌入式系统,嵌入到使用它的应用程序中去。
  • 占用非常少的内存,运行高效可靠,可移植性好。
  • 提供了零配置运行模式。
  • 屏蔽了数据库使用和管理的复杂性,程序仅需进行最基本的数据操作,其他操作可以交给进程内部的数据库引擎完成。
  • 使用模块化设计由八个独立的模块构成,这些独立模块又构成了三个主要的子系统。
  • 接口由SQLite C API组成,因此无论是应用程序、脚本,还是库文件,最终都是通过接口与SQLite交互。
  • 核心代码有C编写,大概有三万多行。

综上,我们可以对SQLite数据库有个大概的了解,并应该知道安卓开发中使用该数据库的原因。
学习过其他数据库的同学应该知道,对数据的操作包括两种,有代码的动态操作,和命令行的直接操作。当然SQLite数据库的命令行操作不是重点我们就大概的讲解一下怎么进入吧,后续操作跟一般数据库的相似。

二、SQLite数据库的命令行操作

首先,讲解一下SQLite数据库自带的一个基于命令行的SQL命令执行工具——sqlite3。
sqlite3工具被集成在Android系统中,用户在Linux的命令行界面中输入sqlite3,启动。
启动Linux的命令行界面的方法是在CMD中打开你在安卓中下载SDK的地址,在打开SDK下的flatform-tools目录,输入adb shell命令,可进入。操作过程如下图:
这里写图片描述
当然,这里很明显的出现查到不到设备的这个错误。所以这里应该注意,把虚拟机启动起来再来查找。

三、代码建库

在编程实现时,一般将所有对数据库的操作都封装在一个类中,因此只要调用这个类,就可以完成对数据库的添加、更新、删除和查询等操作。此处我将链接数据库单独放到一个类中。
这个类继承SQLiteOpenHelper。

import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;    /**     * Created by ASUS on 2017/11/9.     */    public class DBHelpler extends SQLiteOpenHelper{    public static final String SQL = "create table Student(id integer primary key autoincrement, name text,age integer,height integer)";    public DBHelpler(Context context) {        /**构造函数         * 上下文环境context         * Stud.db是数据库名         * 1是数据库版本         */        super(context,"Stud.db",null,1);    }    @Override    public void onCreate(SQLiteDatabase db) {        /**         * 写创建数据库的SQL语句         */        db.execSQL(SQL);    }    @Override    public void onUpgrade(SQLiteDatabase db, int i, int i1) {        /**         * 升级调用该方法         * 如果检测到版本升级了,系统进行调用该方法。         * 删除原来的表再新建         */        db.execSQL("drop table Student");        onCreate(db);    }}

之后所有要链接数据库的增删查改操作可以直接调用该类就可以了。
程序开发人员不应直接调用onCreate()和onUpgrade()函数,而应该是SQLiteOpenHelper类来决定何时调用这两个函数。而SQLiteOpenHelper类的getWritableDatabase()函数getReadableDatabase()函数可以直接调用的。
1、getWritableDatabase()函数:用来建立和打开可读写的数据库对象,一旦函数调用成功了,数据库对象将被缓存,任何需要使用数据库对象时都可以调用这个方法获取到数据库对象。但是在不用的时候一定要调用close()函数关闭数据库。
2、getReadableDatabase()函数:用来调用只读的文件。
对于连接数据库进行操作,有些学过javaWeb开发的同学是比较了解的,此处就不难学习了。我将所有增删查改的种类汇总了一下,写出了个例子,代码放下面了,每一部分的代码都做出了注释。
这里写图片描述
在布局的最下面加入了一个ListView来显示查询结果。
布局文件如下(相对布局):

<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout 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="com.example.asus.sqlite.MainActivity">    <RelativeLayout        android:layout_width="wrap_content"        android:layout_height="wrap_content">        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/name_tv"            android:text="姓名:"            android:textSize="20dp"            android:layout_marginLeft="50dp"            android:layout_marginTop="30dp"/>        <EditText            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/name_ed"            android:hint="请输入姓名"            android:textSize="20dp"            android:layout_marginLeft="20dp"            android:layout_marginTop="20dp"            android:layout_toRightOf="@id/name_tv"            />        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/id_tv"            android:text="身高:"            android:textSize="20dp"            android:layout_marginLeft="50dp"            android:layout_marginTop="20dp"            android:layout_below="@id/name_tv"/>        <EditText            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/id_ed"            android:hint="请输入身高"            android:textSize="20dp"            android:layout_marginLeft="20dp"            android:layout_toRightOf="@id/name_tv"            android:layout_below="@id/name_ed"            />        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/age_tv"            android:text="年龄:"            android:textSize="20dp"            android:layout_marginLeft="50dp"            android:layout_marginTop="20dp"            android:layout_below="@id/id_tv"/>        <EditText            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/age_ed"            android:hint="请输入年龄"            android:textSize="20dp"            android:layout_marginLeft="20dp"            android:layout_toRightOf="@id/age_tv"            android:layout_below="@id/id_ed"            />        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/insert"            android:layout_below="@id/age_tv"            android:layout_marginTop="30dp"            android:layout_marginLeft="20dp"            android:onClick="insert"            android:text="添加数据"/>        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/showall"            android:layout_toRightOf="@id/insert"            android:layout_below="@id/age_tv"            android:layout_marginTop="30dp"            android:onClick="showall"            android:text="显示全部"/>        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/clearshow"            android:layout_toRightOf="@id/showall"            android:layout_below="@id/age_tv"            android:layout_marginTop="30dp"            android:onClick="clearshow"            android:text="清除显示"/>        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/deleteall"            android:layout_toRightOf="@id/clearshow"            android:layout_below="@id/age_tv"            android:layout_marginTop="30dp"            android:onClick="deleteall"            android:text="全部删除"/>        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/checkid_tv"            android:text="ID:"            android:textSize="20dp"            android:layout_below="@id/insert"            android:layout_marginLeft="20dp"/>        <EditText            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/checkid_ed"            android:textSize="20dp"            android:layout_below="@id/insert"            android:layout_toRightOf="@id/checkid_tv"            />        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/deleteid"            android:text="ID删除"            android:layout_marginLeft="20dp"            android:layout_below="@id/insert"            android:layout_toRightOf="@id/checkid_ed"            android:onClick="deleteId"/>        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/selectid"            android:text="ID查询"            android:layout_below="@id/insert"            android:layout_toRightOf="@id/deleteid"            android:onClick="selectId"/>        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/updateid"            android:text="ID更新"            android:layout_below="@id/insert"            android:layout_toRightOf="@id/selectid"            android:onClick="updateId"/>      <ListView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_below="@id/checkid_tv"            android:id="@+id/ListView">        </ListView>    </RelativeLayout></android.support.constraint.ConstraintLayout>

Activity代码如下(当然我在此处做了数据库的增删查改一系列的操作,这些操作可以直接放在链接数据库的类里面,然后在此Activity中只要调用使用就可以了。但是所有写的方法最后都需要调用系统的增删查改的方法来写入数据库中):

import android.content.ContentResolver;import android.content.ContentValues;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.net.Uri;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.EditText;import android.widget.ListView;import android.widget.Toast;import java.util.ArrayList;public class Main2Activity extends AppCompatActivity {    private SQLiteDatabase db;    EditText ed_name;    EditText ed_height;    EditText ed_age;    EditText ed_id;    ListView listView = null;    ArrayList al = new ArrayList();    ArrayAdapter ad;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    public void insert(View view){        /**         * 添加数据         */        //连接数据库        DBHelpler dbHelpler = new DBHelpler(this);        db = dbHelpler.getWritableDatabase();        //获取插入的值        ed_name = (EditText)findViewById(R.id.name_ed);        ed_age = (EditText)findViewById(R.id.age_ed);        ed_height = (EditText)findViewById(R.id.id_ed);        //使用ContentValues类型来传值        ContentValues newvalues = new ContentValues();        newvalues.put("name",ed_name.getText().toString());        newvalues.put("age",ed_age.getText().toString());        newvalues.put("height",ed_height.getText().toString());        //调用系统方法写入数据库的表中        db.insert("Student",null,newvalues);        Toast.makeText(this,"添加成功",Toast.LENGTH_SHORT).show();    }    public void showall(View view){        /**         * 全部显示         */        //连接数据库        DBHelpler dbHelpler = new DBHelpler(this);        db = dbHelpler.getWritableDatabase();        //使用游标进行挨个查找  rawQuery方法就是一种逐行查找的方法        Cursor cursor = db.rawQuery("select * from Student",new String[]{});        clearshow(view);        while (cursor.moveToNext()){            listView = (ListView)findViewById(R.id.ListView);            int id = cursor.getInt(0);            String name = cursor.getString(1);            int age = cursor.getInt(2);            int height = cursor.getInt(3);            al.add("ID: "+id+"--姓名:"+name+"--年龄:"+age+"--身高:"+height);        }        ad  = new ArrayAdapter(this,android.R.layout.simple_list_item_1,al);        listView.setAdapter(ad);    }    public void clearshow(View view){        /**         * 清除显示         */        listView = (ListView)findViewById(R.id.ListView);        al.clear();        ad = new ArrayAdapter(this,android.R.layout.simple_list_item_1,al);        listView.setAdapter(ad);    }    public void deleteall(View view){        /**         * 全部删除         */        //连接数据库        DBHelpler dbHelpler = new DBHelpler(this);        db = dbHelpler.getWritableDatabase();        //系统删除方法        db.delete("Student",null,null);        clearshow(view);        Toast.makeText(this,"全部删除",Toast.LENGTH_SHORT).show();    }    public void deleteId(View view){        /**         * ID删除         */        //连接数据库        DBHelpler dbHelpler = new DBHelpler(this);        db = dbHelpler.getWritableDatabase();        ed_id = (EditText)findViewById(R.id.checkid_ed);        String id = ed_id.getText().toString();        db.delete("Student","id=?",new String[]{id});        Toast.makeText(this,id+"删除成功",Toast.LENGTH_SHORT).show();        clearshow(view);    }    public void selectId(View view){        /**         * ID查询         */        //连接数据库        DBHelpler dbHelpler = new DBHelpler(this);        db = dbHelpler.getWritableDatabase();        //获取输入的ID值        ed_id = (EditText)findViewById(R.id.checkid_ed);        String id0 = ed_id.getText().toString();        //使用游标进行逐行查找        Cursor cursor = db.rawQuery("select * from Student where id = ?",new String[]{id0});        clearshow(view);        while (cursor.moveToNext()){            listView = (ListView)findViewById(R.id.ListView);            int id = cursor.getInt(0);            if (id == Integer.parseInt(id0)){                String name = cursor.getString(1);                int age = cursor.getInt(2);                int height = cursor.getInt(3);                al.add("ID: "+id+"--姓名:"+name+"--年龄:"+age+"--身高:"+height);            }        }        ad  = new ArrayAdapter(this,android.R.layout.simple_list_item_1,al);        listView.setAdapter(ad);    }    public void updateId(View view){        /**         * ID更新         */        //连接数据库        DBHelpler dbHelpler = new DBHelpler(this);        db = dbHelpler.getWritableDatabase();        //获取插入的值        ed_name = (EditText)findViewById(R.id.name_ed);        ed_age = (EditText)findViewById(R.id.age_ed);        ed_height = (EditText)findViewById(R.id.id_ed);        //获取输入的ID值        ed_id = (EditText)findViewById(R.id.checkid_ed);        String id0 = ed_id.getText().toString();        ContentValues contentValues = new ContentValues();        contentValues.put("name",ed_name.getText().toString());        contentValues.put("age",ed_age.getText().toString());        contentValues.put("height",ed_height.getText().toString());        db.update("Student",contentValues,"id=?",new String[]{id0});    }    protected void onStop() {        super.onStop();        if(db!=null)        {            db.close();        }    }}

上述代码演示了,在insert和update时,引入了一个ContentValues对象,它的put方法将插入或者更新的数据写入对象中,再调用系统的方法来写入数据库中。查询中引入了数据库常用的游标cursor。学习会以上的代码后,相信读者都可以在自己开发的软件上使用SQLite数据库存储数据。祝大家成功!

原创粉丝点击