Android 数据存储之SQLite数据库存储

SQLite本身就是一个独立的第三方库,包含2T的容量,有自己的语法,Android集成了SQlite数据库。

SQLite中的数据类型 有五种储存类型
NULL 空
INTEGER 整型
REAL 浮点型
TEXT 文本
BLOB 普通数据

Android中获取数据库对象:

SQLiteDatebase db= myOpenHelper.getWriteableDatebase();
//如果磁盘内存未满着调用getWritableDatabase(),如果磁盘内存满了,就用只读模式开启数据库 SQLiteDatabase
db = mySQLite.getReadableDatabase();

SQLite数据库主要包含了:增、删、改、查, 四个方面
在Android中主要有两种方式来实现SQLite数据库的,增、删、改、查
提供一个帮助类SQLiteOpenHelper,用自己实现类继承即可

第一种———是使用SQLite语句来实现:
分别调用:

db.execSQL (SQLite语句,?数据集合)
db.rawQuery(SQLite语句,?数据集合)

所以SQLite可以解析大部分标准SQL语句,如:
查询语句: select * from 表名 where 条件子句 group by 分组字句 having ...order by 排序子句
如:select * from person
select * from person order by id desc
selsct name from person group bu name having count(*)>1
分页SQL与mysql类型,下面SQL语句获取5条记录,跳转前面3条记录
select * from Account limit 5offset 3 或者 select * from Account limit 3,5
插入语句:insert into 表名 (字段列表) values (值列表)。如: insert into person (name,age) values ('快发' , 3)
更新语句:update 表名 set 字段名=值 where 条件子句。如:update person ser name='快发' where id = 10
删除语句:delete from 表名 where 条件子句。如:delete from person where id= 10

获取添加记录后自增长的ID值: SELECT last_insert_rowid( )

第二种——是使用Android提供的API实现:

insert() 它接收三个参数,第一个参数是表名,我们希望向哪张表里添加数据,这里就传入该表的名字。
第二个参数用于在未指定添加数据的情况下给某些可为空的列自动赋值 NULL,一般我们用不到这个功能,
直接传入 null 即可。第三个参数是一个 ContentValues 对象,它提供了一系列的 put()方法重载,用于向
ContentValues 中添加数据,只需要将表中的每个列名以及相应的待添加数据传入即可.

update() 这个方法接收四个参数,第一个参数和 insert()方法一样,也是表名,在这里指定去更新哪张表里的数据。第二个参数是
ContentValues 对象,要把更新数据在这里组装进去。第三、第四个参数用于去约束更新某一行或某几行中的数据,不指定的话默认就是更新所有行。

delete() 这个方法接收三个参数,第一个参数仍然是表名,这个已经没什么好说的了,第二、第三个参数又是用于去约束删除某一
行或某几行的数据,不指定的话默认就是删除所有行。

query() 第一个参数不用说,当然还是表名,表示我们希望从哪张表中查询数据。
第二个参数用于指定去查询哪几列,如果不指定则默认查询所有列。
第三、第四个参数用于去约束查询某一行或某几行的数据,不指定则默认是查询所有行的数据。
第五个参数用于指定需要去 group by 的列,不指定则表示不对查询结果进行 group by 操作。
第六个参数用于对 group by 之后的数据进行进一步的过滤,不指定则表示不进行过滤。
第七个参数用于指定查询结果的排序方式,不指定则表示使用默认的排序方式。


这里写图片描述

帮助类MySQLite代码:

package com.example.administrator.foundationdemo.sqlite.service;

import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Administrator on 2016/12/12.
 */
public class MySQLite  extends SQLiteOpenHelper{

    public MySQLite (Context context,String name){//保存路径  <包>/datebases/
        this(context,name,null,2);
    }

    public MySQLite(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    public MySQLite(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
        super(context, name, factory, version, errorHandler);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {//数据库第一次被创建时调用
        //创建表                             表名称  自增长ID名
        sqLiteDatabase.execSQL("CREATE TABLE person (personId integer primary key autoincrement,name varchar(20))");

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {//版本号发生修改时调用
        //给表增加已给字段
        sqLiteDatabase.execSQL("ALTER TABLE person ADD phone VARCHAR(12) NULL");


    }
}

操作类PersonSQLite代码:

package com.example.administrator.foundationdemo.sqlite.service;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;


import com.example.administrator.foundationdemo.sqlite.domain.Person;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/12/12.
 */
public class PersonSQLite {

    private MySQLite mySQLite;
    private Context context;
    public PersonSQLite(Context context){
        this.context = context;
        mySQLite = new MySQLite(context,"mySQLite");
    }

    //增
    public void save(Person person){
        SQLiteDatabase db = mySQLite.getWritableDatabase();
        /**
         * 方法一:Androiod集成API,用于SQLite数据库增加数据
         */
//        ContentValues values = new ContentValues();
//                 //参数键 值
//        values.put("name",person.getName());
//        values.put("phone",person.getPhone());
//                //表名          参数集合
//        db.insert("person",null,values);//NULL值字段,及可以为空的字段,如果db.insert("person","name",null);及name为NULL不会报错,如果均为空着会报错
        /**
         * 方法二:execSQL,SQLite 语句添加,可练习SQLite语句的熟练度
         */
                  //增加的SQLite语句                                          根据前面问号顺序排列的值
        db.execSQL("insert into person (name,phone) values (?,?)",new Object[]{person.getName(),person.getPhone()});
        db.close();//关闭数据库

    }
    //删
    public void delete(Integer id){
        SQLiteDatabase db = mySQLite.getWritableDatabase();
        /**
         * 方法一:Androiod集成API,用于SQLite数据删除数据
         */
//        db.delete("person","personId=?",new String[]{id.toString()});
        /**
         * 方法二:execSQL,SQLite 语句删除,可练习SQLite语句的熟练度
         */
        db.execSQL("delete from person where personId=?",new Object[]{id});
        db.close();//关闭数据库
    }
    //改
    public void update(Person person){
        SQLiteDatabase db = mySQLite.getWritableDatabase();
        /**
         * 方法一:Androiod集成API,用于SQLite数据库更新数据
         */
//        ContentValues values = new ContentValues();
//        //参数键 值
//        values.put("name",person.getName());
//        values.put("phone",person.getPhone());
//        db.update("person", values, "personId=?", new String[]{person.getId()+""});
        /**
         * 方法二:execSQL,SQLite 语句更新,可练习SQLite语句的熟练度
         */
        db.execSQL("update person set name=?,phone=? where personId=?",new Object[]{person.getName(),person.getPhone(),person.getId()});
        db.close();//关闭数据库
    }
    //查
    public Person find(Integer id){
        SQLiteDatabase db = mySQLite.getReadableDatabase();//如果磁盘内存未满着调用getWritableDatabase(),如果磁盘内存满了,就用只读模式开启数据库
        /**
         * 方法一:Androiod集成API,用于SQLite数据库查找数据
         */
                           //数据集合null及全部
//        db.query("person",null, "personId=?", new String[]{id.toString()},null,null,null);
        /**
         * 方法二:execSQL,SQLite 语句查找,可练习SQLite语句的熟练度
         */

        Cursor cursor = db.rawQuery("select * from person where personId=?", new String[]{id.toString()});//获得游标
        if (cursor.moveToFirst()){//判断数据是否存在
            int personId = cursor.getInt(cursor.getColumnIndex("personId"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String phone = cursor.getString(cursor.getColumnIndex("phone"));
            cursor.close();
            return new Person(personId,name,phone);
        }else {
            cursor.close();
            Toast.makeText(context,"数据不存在!",Toast.LENGTH_SHORT).show();
            return null;
        }

    }
    //分页查询
    public List<Person> getScrollDate(int offset,int maxResult){

        List<Person> list = new ArrayList<Person>();
        SQLiteDatabase db = mySQLite.getReadableDatabase();//如果磁盘内存未满着调用getWritableDatabase(),如果磁盘内存满了,就用只读模式开启数据库

        /**
         * 方法一:Androiod集成API,用于SQLite数据库查找数据
         */

//        db.query("person",null,null ,null,null,"personId asc",offset+","+maxResult);
        /**
         * 方法二:execSQL,SQLite 语句查找,可练习SQLite语句的熟练度
         */

        //将数据库表person按personId升序排列在分页  asc|desc ==>升序|降序
        Cursor cursor = db.rawQuery("select * from person order by personId asc limit ?,?", new String[]{String.valueOf(offset),String.valueOf(maxResult)});
        while (cursor.moveToNext()){//移动游标

            int personId = cursor.getInt(cursor.getColumnIndex("personId"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String phone = cursor.getString(cursor.getColumnIndex("phone"));
            list.add(new Person(personId,name,phone));
        }
        cursor.close();//关闭指针
        return list;
    }
    //统计数据库记录
    public long getCount(){
        SQLiteDatabase db = mySQLite.getReadableDatabase();//如果磁盘内存未满着调用getWritableDatabase(),如果磁盘内存满了,就用只读模式开启数据库
        /**
         * 方法一:Androiod集成API,用于SQLite数据库查找数据
         */

//        db.query("person",new String[]{"count(*)"},null ,null,null,null,null);
        /**
         * 方法二:execSQL,SQLite 语句查找,可练习SQLite语句的熟练度
         */
        //将数据库表person按personId升序排列在分页
        Cursor cursor = db.rawQuery("select count(*) from person ", null);
        cursor.moveToFirst();
        long result = cursor.getLong(0);
        cursor.close();
        return result;
    }
}

实例类person代码:

package com.example.administrator.foundationdemo.sqlite.domain;

/**
 * Created by Administrator on 2016/12/12.
 */
public class Person {
    private int id;
    private String name;
    private String phone;

    public Person(){

    }

    public Person(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }

    public Person(int id, String name, String phone) {
        this.id = id;
        this.name = name;
        this.phone = phone;
    }

    public int getId() {

        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

测试Activity代码:

package com.example.administrator.foundationdemo.sqlite;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.foundationdemo.R;
import com.example.administrator.foundationdemo.sqlite.domain.Person;
import com.example.administrator.foundationdemo.sqlite.service.MySQLite;
import com.example.administrator.foundationdemo.sqlite.service.PersonSQLite;

import java.util.List;

public class SQLiteActivity extends AppCompatActivity {

    private EditText person_name_edittext;
    private EditText person_phone_edittext;
    private EditText person_id_edittext;
    private EditText person_num1_edittext;
    private EditText person_num2_edittext;
    private TextView text;
    private PersonSQLite personSQLite;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sqlite);
        init();
    }

    public void onClick(View view){
        switch (view.getId()){
            case R.id.save_sql_button:
                personSQLite.save(new Person(person_name_edittext.getText().toString(),person_phone_edittext.getText().toString()));
                break;
            case R.id.delete_sql_button:
                String personId = person_id_edittext.getText().toString();
                if (null == personId||"".equals(personId)){
                    person_id_edittext.setVisibility(View.VISIBLE);
                    person_id_edittext.setHint("请输入删除personId");
                }else {
                    personSQLite.delete(Integer.parseInt(personId));
                    person_id_edittext.setText("");
                    person_id_edittext.setVisibility(View.GONE);
                }
                break;
            case R.id.update_sql_button:

                break;
            case R.id.find_sql_button:
                String personId1 = person_id_edittext.getText().toString();
                if (null == personId1||"".equals(personId1)){
                    person_id_edittext.setVisibility(View.VISIBLE);
                    person_id_edittext.setHint("请输入查询personId");
                }else {
                    Person person = personSQLite.find(Integer.parseInt(personId1));
                    if (person==null){
                        Toast.makeText(this,"无结果",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    text.setText("personId:"+person.getId()+"\nname:"+person.getName()+"\nphone"+person.getPhone());
                    person_id_edittext.setText("");
                    person_id_edittext.setVisibility(View.GONE);
                }
                break;
            case R.id.scroll_date_sql_button:
                String num1 = person_num1_edittext.getText().toString();
                String num2 = person_num2_edittext.getText().toString();
                if (null == num1||"".equals(num1)||null == num2||"".equals(num2)){
                    person_num1_edittext.setVisibility(View.VISIBLE);
                    person_num2_edittext.setVisibility(View.VISIBLE);
                }else {
                    List<Person> list = personSQLite.getScrollDate(Integer.parseInt(num1),Integer.parseInt(num2));
                    if (list==null){
                        Toast.makeText(this,"无结果",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    for (Person person : list){
                        text.setText(text.getText().toString()+"\npersonId:"+person.getId()+"\nname:"+person.getName()+"\nphone"+person.getPhone());
                    }
                    person_num1_edittext.setText("");
                    person_num2_edittext.setText("");
                    person_num1_edittext.setVisibility(View.GONE);
                    person_num2_edittext.setVisibility(View.GONE);
                }
                break;
            default:
                break;
        }
    }

    private void init(){
        person_name_edittext = (EditText) findViewById(R.id.person_name_edittext);
        person_phone_edittext = (EditText)findViewById(R.id.person_phone_edittext);
        person_id_edittext = (EditText) findViewById(R.id.person_id_edittext);
        person_num1_edittext = (EditText)findViewById(R.id.person_num1_edittext);
        person_num2_edittext = (EditText) findViewById(R.id.person_num2_edittext);
        text = (TextView) findViewById(R.id.text);
        personSQLite = new PersonSQLite(this);
    }

}

XML布局代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    style="@style/MatchMatch"
    android:orientation="vertical"
    tools:context="com.example.administrator.foundationdemo.sqlite.SQLiteActivity">

    <EditText
        android:id="@+id/person_name_edittext"
        style="@style/MatchWrap"
        android:hint="请输入数据类容name"/>
    <EditText
        android:id="@+id/person_phone_edittext"
        style="@style/MatchWrap"
        android:inputType="number"
        android:hint="请输入数据类容phone"/>
    <EditText
        android:id="@+id/person_id_edittext"
        style="@style/MatchWrap"
        android:inputType="number"
        android:visibility="gone" />
    <EditText
            android:id="@+id/person_num1_edittext"
            style="@style/MatchWrap"
            android:inputType="number"
            android:visibility="gone"
            android:hint="请输入跳过条数"/>
    <EditText
            android:id="@+id/person_num2_edittext"
            style="@style/MatchWrap"
            android:inputType="number"
            android:visibility="gone"
            android:hint="请输入查询条数"/>

    <LinearLayout
        android:orientation="horizontal"
        style="@style/MatchWrap">
        <Button
            android:id="@+id/save_sql_button"
            style="@style/WrapWrap"
            android:onClick="onClick"
            android:text="增加数据"/>
        <Button
            android:id="@+id/delete_sql_button"
            style="@style/WrapWrap"
            android:onClick="onClick"
            android:text="删除数据"/>
        <Button
            android:id="@+id/update_sql_button"
            style="@style/WrapWrap"
            android:onClick="onClick"
            android:text="修改数据"/>
        <Button
            android:id="@+id/find_sql_button"
            style="@style/WrapWrap"
            android:onClick="onClick"
            android:text="查询数据"/>
    </LinearLayout>
    <Button
        android:id="@+id/scroll_date_sql_button"
        style="@style/WrapWrap"
        android:onClick="onClick"
        android:text="查询数据列表"/>
    <TextView
        android:id="@+id/text"
        style="@style/WrapWrap"/>

</LinearLayout>

效果图:

这里写图片描述
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,719评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,337评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,887评论 0 324
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,488评论 1 266
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,313评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,284评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,672评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,346评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,644评论 1 293
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,700评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,457评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,316评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,706评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,990评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,261评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,648评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,859评论 2 335

推荐阅读更多精彩内容