最近利用下班时间,找了看什么书比较适合初学android的朋友,很多人推荐了这本书,于是就买了一本,感觉看书,思考,动手,再思考和总结这样过程还是很有必要的,于是就打算把自己学习的东西简单的总结一下;方便自己以后查找,也有利于学习的巩固。在这里首先要感谢一下书籍的作者——郭霖前辈。
关于数据持久化,我在前两篇分别介绍了通过文件和SP的形式,今天就来介绍一下通过Android内置轻量级数据库SQLite来实现。这里只会介绍一下最基本的使用流程,不会延伸。在下一篇会简单介绍一下LitePal开源库的使用。好了,下面就来看看Android内置数据库的基本使用吧。示例代码下载链接
1,使用步骤
- (1)自定义一个类继承SQLiteOpenHelper,重写里面的两个抽象方法onCreate()和onUpdate()
- (2)实例化一个自定义类,通过getReadableDatabase()或者getWriteableDatabase()获取数据库对象;这两个方法的区别也很明显,也即当数据不可写入的时候,前者不会出异常,后者则会出现异常。
- (3)通过该数据库对象对数据进行操作,比如CRUD(添加,查询,更新,删除数据等操作)
2,示例代码
MySQLiteHelper.java代码:
package com.hfut.operationsqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
/**
* author:why
* created on: 2018/3/18 10:43
* description:
*/
public class MySQLiteHelper extends SQLiteOpenHelper {
//数据类型可以有integer,text(文本),real(浮点型),blob(二进制类型)
public static final String createStudentSql="create table student(" +
"stuID integer primary key autoincrement," +
"name text," +
"age integer," +
"sex text)";
public static final String createTeacherSql="create table teacher(" +
"name text," +
"teacherID," +
"subject text)";
private Context myContext;
public MySQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
this.myContext=context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createStudentSql);
db.execSQL(createTeacherSql);
Toast.makeText(myContext,"执行了数据库创建操作",Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists student");
db.execSQL("drop table if exists teacher");
onCreate(db);
}
}
SQLiteActivity.java代码:
package com.hfut.operationsqlite;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class SQLiteActivity extends AppCompatActivity {
private MySQLiteHelper mySQLiteHelperBase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sqlite);
mySQLiteHelperBase = new MySQLiteHelper(this, "class", null, 1);
// mySQLiteHelperBase=new MySQLiteHelper(this,"class",null,2);
}
//创建数据库
public void createDB(View view) {
mySQLiteHelperBase.getReadableDatabase();
}
//更新数据库
public void updateDB(View view) {
mySQLiteHelperBase.getReadableDatabase();
}
//操作数据库
public void operateDB(View view) {
Intent intent =new Intent("com.why");
startActivity(intent);
}
}
OperateActivity.java代码:
package com.hfut.operationsqlite;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class OperateActivity extends AppCompatActivity {
private static final String TAG = "OperateActivity";
private MySQLiteHelper mySQLiteHelper;
SQLiteDatabase sqLiteDatabase;
ContentValues contentValues;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_operate);
initData();
}
private void initData() {
mySQLiteHelper = new MySQLiteHelper(this, "class", null, 1);
sqLiteDatabase = mySQLiteHelper.getReadableDatabase();
contentValues = new ContentValues();
sharedPreferences=getSharedPreferences("studentTableData",MODE_PRIVATE);
}
public void insertData(View view) {
contentValues.put("name", "why");
contentValues.put("age", 26);
contentValues.put("sex", "male");
sqLiteDatabase.insert("student", null, contentValues);
contentValues.clear();
contentValues.put("name", "jr");
contentValues.put("age", 24);
contentValues.put("sex", "female");
sqLiteDatabase.insert("student", null, contentValues);
contentValues.clear();
contentValues.put("name", "xiaoming");
contentValues.put("age", 34);
contentValues.put("sex", "unkown");
sqLiteDatabase.insert("student", null, contentValues);
contentValues.clear();
System.out.println(TAG+"执行了添加操作");
}
public void deleteData(View view) {
// sqLiteDatabase.execSQL("delete from student where name=?",new String[]{"xiaoming"});
sqLiteDatabase.delete("student", "name=?", new String[]{"xiaoming"});
System.out.println(TAG+"执行了删除操作");
}
public void updateData(View view) {
//sqLiteDatabase.execSQL("update student set age=20 where name='jr'");
contentValues.put("age", 20);
sqLiteDatabase.update("student", contentValues, "name=?", new String[]{"jr"});
contentValues.clear();
System.out.println(TAG+"执行了更新操作");
}
public void queryData(View view) {
StringBuilder stringBuilder=new StringBuilder();
//查询所有结果,按照年龄排序
Cursor cursor = sqLiteDatabase.query("student", null, null, null, null, null, "age");
//遍历所有数据,并保存到SP中
if(cursor.moveToFirst()){
do{
String name=cursor.getString(cursor.getColumnIndex("name"));
String sex=cursor.getString(cursor.getColumnIndex("sex"));
int age =cursor.getInt(cursor.getColumnIndex("age"));
int stuID=cursor.getInt(cursor.getColumnIndex("stuID"));
stringBuilder.append("\nstuID="+stuID+";name="+name+";age="+age+";sex="+sex+"\n");
}while(cursor.moveToNext());
}
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("student表数据:",stringBuilder.toString());
editor.apply();
System.out.println(TAG+"执行了查询操作");
}
}
activity_sqlite.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.hfut.operationsqlite.SQLiteActivity">
<Button
android:layout_marginTop="20dp"
android:textSize="20dp"
android:onClick="createDB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="创建数据库"
/>
<Button
android:layout_marginTop="15dp"
android:textSize="20dp"
android:onClick="updateDB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="更新数据库"
/>
<Button
android:layout_marginTop="15dp"
android:textSize="20dp"
android:onClick="operateDB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="操作数据库"
/>
</LinearLayout>
activity_operate.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.hfut.operationsqlite.OperateActivity">
<Button
android:textSize="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="insertData"
android:text="添加数据" />
<Button
android:textSize="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:onClick="deleteData"
android:text="删除数据" />
<Button
android:textSize="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:onClick="updateData"
android:text="更新数据" />
<Button
android:textSize="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:onClick="queryData"
android:text="查询数据" />
</LinearLayout>
3,运行结果
第一步:运行程序
第二步:点击“创建数据库”按钮
第三步:调整代码,在实例化自定义类的时候,最后一个参数是数据库版本,我们想要执行update()方法,就必须要求这个值比已经存在的值要大(整形)。
第四步:点击“操作数据库”按钮
第五步:点击“添加数据”按钮
第六步:点击“删除数据”按钮
第七步:点击“更新数据”按钮
第八步:点击“查询数据”按钮
注:我在最后查询数据的时候,把查询到的数据通过SP存储起来了;结果在第八步可以查看;更多关于SP的介绍;请查看我上一篇博客。关于在dos窗口中操作的指令主要有以下:
- (1)前提,首先安装ADB并配置环境变量
- (2)找到APP路径,这里是/data/data/com.hfut.operationsqite/databases/;通过cd进入
- (3)通过ls查看文件夹里面的文件列表
- (4)通过sqlite3+数据库名称进入数据库
- (5)通过.table查询数据库中的数据表
- (6)通过.schema语句查看数据表创建语句
- (7)还有就是sql查询语句,这个就不多说了,都是很简单的(查询五子句会了就Ok了)
其他的关于SQLite数据库对象的相关方法(insert(),update(),delete(),query())以及参数就不细说了。尤其查询的方法,参数实在太多了,但是它越是多,我就越是单独说一下,也就是多并不难,它的参数如下:
- (1)table 数据表名称
- (2)columns 指定查询的列
- (3)selection 对应sql中的where
- (4)selectionArgs selection(where)条件中的占位符通过值
- (5)groupby 指定需要分组的列,比如对于上述class表,可以对sex列分为男/女组
- (6)having 对应sql中having子句,也就是对分组后的结果进一步约束
- (7)orderby 排序,选择按某一列排序,比如年龄
所以,这么看还是很简单的,只要熟悉sql语句,理解起来很easy;但是容易理解又觉得繁琐,所以后面肯定用的不多了,这样我们还不如直接操作原生的sql语句了。所以下一篇我们将会介绍LitePal开源库的基本使用。
总结:这一部分基本上就结束了,在程序中我们还巩固了前一篇学习的SP知识,让我们继续一起努力学习吧。
注:欢迎扫码关注