您的位置:首页 > 移动开发 > Android开发

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

2016-12-13 18:15 232 查看
SQLite本身就是一个独立的第三方库,包含2T的容量,有自己的语法,Android集成了SQlite数据库。

SQLite中的数据类型 有五种储存类型

NULL 空

INTEGER 整型

REAL 浮点型

TEXT 文本

BLOB 普通数据

Android中获取数据库对象:

SQLiteDatebase db= myOpenHelper.getWriteableDatebase();

//如果磁盘内存未满着调用getWritableDatabase(),如果磁盘内存满了,就用只读模式开启数据库 SQLiteDatabase

db = mySQLite.getReadableDatabase();

SQLite数据库主要包含了:增、删、改、查, 四个方面

在Android中主要有两种方式来实现SQLite数据库的,增、删、改、查

提供一个帮助类SQLiteOpenHelpe
4000
r,用自己实现类继承即可

第一种———是使用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>


效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: