文章目录
####1、SQLite数据库简介
SQLite 是一款轻量级的关系型数据库,它的运算速度非常快,占用资源也非常少。通常只需要几百KB 的内存就够了,因而特别适用于移动设备上。
####2、数据库的创建简介
Android 为了让我们非常方便的管理一个数据库,专门提供一个SQLiteOpenHelper帮助类,借助这个类我们可以对数据库进行创建,升级。
1)SQLiteOpenHelper 是一个抽象类,这意味着我们使用它的话就需要创建一个自己的帮助类来继承它。
2) SQLiteOpenHelper 有两个抽象方法 onCreat() onUpgrade() ,我们必须在自己的帮助类里面来重写它,实现创建和升级的代码逻辑。
3)SQLiteOpenHelper 还有两个非常重要的实例方法,getReadableDataase() WritableDatabase() 这两个方法都创建或打开一个数据库(已存在),并返回一个可以对数据库进行读写的对象。
4)当磁盘满的时候, getReadableDataase 将以只读的形式返回数据库对象,WritableDatabase 会出现错误
5)SQLiteOpenHelper 有两个构造方法可以重写,一般使用参数少一点的那个即可。四个参数:
第一个参数 Context : 必须有它才能对数据库进行操作
第二个参数:数据库名,创建数据库时使用的名字
第三个参数:允许我们在查询时返回的Cursor ,一般传入null
第四个参数:当前数据库的版本号,可用于数据库升级。
6)创建的数据库放在 /data/data/“package name”/database/ 目录下面
这里我们就创建一个数据库实例:
数据库名称: BookStore.db
添加一张表:Book
表中有id(主键) 、 作者、 价格、 页数、 书名 等列
create table Book (
id integer primary key autoincrement,
author text,
price real,
pages integer,
name text
)
SQLite 的数据类型:
integer 表示整型
real 表示浮点型
text 表示文本类型
blob 表示二进制类型
上述语句我们把primary key 列设为主键, 并用autoincrement 关键字表示id 列是自增长的。
####3、一个示例
创建 一个数据库 用于保存 学生的 : 姓名 性别 年龄 学号
####4、代码架构
####5、主要代码
activity_main.xml 文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.example.menglux.mysqlitedata.MainActivity">
<Button
android:id="@+id/creat_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="创建"
android:textSize="30dp"/>
<Button
android:id="@+id/add_one_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="添加 one"
android:textSize="30dp"/>
<Button
android:id="@+id/add_two_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="添加 two"
android:textSize="30dp"/>
<Button
android:id="@+id/update_one_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="修改 one "
android:textSize="30dp"/>
<Button
android:id="@+id/search_all_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="查找全部"
android:textSize="30dp"/>
<Button
android:id="@+id/search_condition_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="条件查找"
android:textSize="30dp"/>
<Button
android:id="@+id/delate_two_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="删除 two"
android:textSize="30dp"/>
<Button
android:id="@+id/delate_all_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="删除 全部"
android:textSize="30dp"/>
</LinearLayout>
MainActivity.java
package com.example.menglux.mysqlitedata;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private String TAG = "MainActivity: ";
private Button buttonCreat, buttonAddOne, buttonAddTwo, buttonUpdate,
buttonSearchAll, buttonSearchCondition,buttonDelateTwo,buttonDelateAll;
private SQLiteDatabase db;
private DataBaseOperation dop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initvView(); //初始化组建信息
}
//初始化组建信息
private void initvView() {
buttonCreat = (Button) findViewById(R.id.creat_id);
buttonAddOne = (Button) findViewById(R.id.add_one_id);
buttonAddTwo = (Button) findViewById(R.id.add_two_id);
buttonUpdate = (Button) findViewById(R.id.update_one_id);
buttonSearchAll = (Button) findViewById(R.id.search_all_id);
buttonSearchCondition = (Button) findViewById(R.id.search_condition_id);
buttonDelateTwo = (Button) findViewById(R.id.delate_two_id);
buttonDelateAll = (Button) findViewById(R.id.delate_all_id);
buttonCreat.setOnClickListener(this);
buttonAddOne.setOnClickListener(this);
buttonAddTwo.setOnClickListener(this);
buttonUpdate.setOnClickListener(this);
buttonSearchAll.setOnClickListener(this);
buttonSearchCondition.setOnClickListener(this);
buttonDelateTwo.setOnClickListener(this);
buttonDelateAll.setOnClickListener(this);
dop = new DataBaseOperation(this, db); //实例化数据库对象
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.creat_id: //创建数据库,若已经存在就打开
dop.create_db();
dop.close_db();
break;
case R.id.add_one_id: //向数据库添加 一个学生 one : 姓名 性别 年龄 学号
dop.create_db();
dop.insert_db("lum","boy",26,"528");
dop.close_db();
break;
case R.id.add_two_id: //向数据库添加 一个学生 two : 姓名 性别 年龄 学号
dop.create_db();
dop.insert_db("who","girl",24,"520");
dop.close_db();
break;
case R.id.update_one_id: // 更新学生 根据学号 更新 one 的 姓名 年龄
dop.create_db();
dop.update_one("lumeng",28,"528");
dop.close_db();
break;
case R.id.search_all_id: //查找数据库全部信息
dop.create_db();
Cursor cursor = dop.query_db();
if (cursor.getCount() > 0) { //如果数据库里查询到数据
while (cursor.moveToNext()) {// 光标移动成功
String str_name = cursor.getString(cursor
.getColumnIndex("name")); // 获得姓名
String str_sex = cursor.getString(cursor
.getColumnIndex("sex")); // 获得性别
int int_age = cursor.getInt(cursor
.getColumnIndex("age")); // 获得年龄
String str_id = cursor.getString(cursor
.getColumnIndex("id")); // 获得学号
System.out.println(TAG + "姓名: " + str_name + " 性别:" + str_sex + " 年龄:" + int_age
+ " 学号:" + str_id);
}
}
dop.close_db();
break;
case R.id.search_condition_id: //依照性别 boy 查找 学生
dop.create_db();
Cursor cursor_sex = dop.query_sex("boy");
if (cursor_sex.getCount() > 0) { //如果数据库里查询到数据
while (cursor_sex.moveToNext()) {// 光标移动成功
String str_name = cursor_sex.getString(cursor_sex
.getColumnIndex("name")); // 获得姓名
String str_sex = cursor_sex.getString(cursor_sex
.getColumnIndex("sex")); // 获得性别
int int_age = cursor_sex.getInt(cursor_sex
.getColumnIndex("age")); // 获得年龄
String str_id = cursor_sex.getString(cursor_sex
.getColumnIndex("id")); // 获得学号
System.out.println(TAG + "姓名: " + str_name + " 性别:" + str_sex + " 年龄:" + int_age
+ " 学号:" + str_id);
}
}
dop.close_db();
break;
case R.id.delate_two_id: //根据学号 删除学生 two
dop.create_db();
dop.delate_two("520");
dop.close_db();
break;
case R.id.delate_all_id: //删除 全部学生
dop.create_db();
dop.delate_all();
dop.close_db();
break;
default:
break;
}
}
}
DataBaseOperation.java
package com.example.menglux.mysqlitedata;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;
/**
* Created by lum on 2018/5/6.
*/
public class DataBaseOperation {
private final String TAG = "DataBaseOperation: ";
private SQLiteDatabase db;
private Context context;
public DataBaseOperation(Context context, SQLiteDatabase db) {
this.db = db;
this.context = context;
}
//数据库的打开或创建 db name student.db
public void create_db() {
db = SQLiteDatabase.openOrCreateDatabase(context.getFilesDir().toString() + "/student.db", null);
if (db == null) { //判断数据库是否创建成功
System.out.println(TAG + "数据库创建失败" );
}
//创建表,tab name 名称为 record ,主键id
db.execSQL("create table if not exists record(_id integer primary key autoincrement,"
+ "name varchar(30)," // 姓名
+ "sex text," //性别
+ "age integer," //年龄
+ "id text" + ")");//学号
System.out.println(TAG + "数据库创建成功" );
}
//插入备忘录信息到数据库
public void insert_db(String name,String sex,int age,String id) {
db.execSQL("insert into record(name,sex,age,id) values('"
+ name //姓名
+ "','"
+ sex //性别
+ "','"
+ age //年龄
+ "','"
+ id //学号
+ "');");
System.out.println(TAG + "插入新的数据库信息" );
}
//根据学号 更新学生 one 的 姓名 年龄
public void update_one( String name,int age , String id) {
db.execSQL("update record set name='" + name
+ "',age='" + age
+ "'where id='" + id + "'");
System.out.println(TAG + "修改学生 one 资料" );
}
//查询所有内容
public Cursor query_db() {
Cursor cursor = db.rawQuery("select * from record", null);
System.out.println(TAG + "查找全部数据库信息" );
return cursor;
}
//根据性别查找
public Cursor query_sex(String sex) {
Cursor cursor = db.rawQuery("select * from record where sex='" + sex
+ "';", null);
System.out.println(TAG + "根据性别查找" + sex );
return cursor;
}
// select * from 表名 where 学号 between '开始学号' and '结束学号' // 学号段查询
public Cursor query_duing_id(String startid, String endid) {
Cursor cursor = db.rawQuery("select * from record where id >='" + startid + "'and timeedit<='"
+ endid + "';", null);
System.out.println(TAG + "学号段查询" );
return cursor;
}
// select * from 表名 where content like '%abc%' //模糊查询 查找全表中 姓名包含 关键字的学生
public Cursor query_content(String keword) {
Cursor cursor = db.rawQuery("select * from record where name like '%"
+ keword + "%';", null);
System.out.println(TAG + "关键字模糊查询" );
return cursor;
}
//根据学号 删除 学生 two
public void delate_two( String id ) {
db.execSQL("delete from record where id='" + id + "'");
System.out.println(TAG + "删除学生 two");
}
//删除表全部内容 不删除表
public void delate_all( ) {
db.execSQL("delete from record" );
System.out.println(TAG + "清空表内容");
}
// 关闭数据库
public void close_db() {
db.close();
System.out.println(TAG + "关闭数据库");
}
}
数据库 demo 下载
可用于在一个activity 创建数据库,在另一个activity 打开数据库
文件参考:
android之存储篇_SQLite数据库_让你彻底学会SQLite的使用