跟我学Android之十三 SQLite数据库操作

视频课:https://edu.csdn.net/course/play/7621

本章内容

 1 节  SQLite 数据库概述

 2 节  SQLite 建库建表

 3 节 管理数据库连接

 4    操作数据库数据

 5    数据绑定

本章目标

掌握 SQLite 数据的基本特点与工具使用。

熟练掌握 SQLite 建库建表的方法。

熟练掌握连接 SQLite 数据库的方法。

熟悉 SQLite 数据库的升级与建立方法。

掌握通过数据绑定完成数据显示的方法。

SQLite数据库简介

SQLite是一种非常流行的嵌入式数据库,是由C语言编写而成,是一款轻型关系型数据库,支持SQL,支持多种操作系统,完全独立运行,没有依赖性,Android内嵌了SQLite数据库。 


SQLite数据库工具是用来操作数据库文件的工具,官方网站提供了命令行工具的下载。 


http://www.sqlite.org/download.html


下载sqlite-shell-******.zip文件

解压缩后只有一个文件sqlite3,将sqlite3所在的路径加入path环境变量,Sqlite3工具的使用,连接数据库文件。

$ sqlite3 <数据库文件路径>

SQLite数据库工具是用来操作数据库文件的工具

uSqlite3工具的使用

Ø数据库的相关管理命令都是以.开头,常用命令如下

 

SQLite数据库工具是用来操作数据库文件的工具

sqlite3工具的使用,在sqlite3的命令行下可以直接输入标准sql语句,除了sqlite3以外,还有很多非官方的可视化管理工具

SQLite Database Browser

SQLite Expert Professional

SQLite Develope

SQLite与大型数据库的区别

两者都是支持关系的关系型数据库,SQLite是一个嵌入型的轻量级数据库,适合小数据量,大型数据库独立运行在数据库服务器上,适合大数据量级别,大型数据库通常以网络的方式对外提供服务。



创建 SQLite 数据库 


$ sqlite3test.db


直接在命令行输入上面的命令,如果test.db不存在,则预创建(直到执行相关sql才创建文件),如果test.db存在,则连接数据库 


$ sqlite3test.db <sql.script


上述命令可以在创建数据库的同时使用sql.script进行初始化 


SQLite数据库的数据类型

SQLite数据中的列可以存储任意数据类型的数据


为了与其他数据库兼容,可以为字段指定默认的类型

NULL:空值

INTEGER: 带符号的整数,具体取决于存入数字的范围大小

REAL:浮点数,存储为8-bytes的浮点数

TEXT:字符串文本

BLOB:二进制对象

同时还接受如下一些类型:

smallint 16位整数

int 32位整数

float 32位浮点数

double 64位浮点数

SQLite数据库的数据类型

为了与其他数据库兼容,可以为字段指定默认的类型

同时还接受如下一些类型:

char(n) n不能炒作254

varchar(n) n不能超过4000

date

time

limestamp

创建SQLite数据表,通过SQL语句创建表 

create table books (id integer primary key autoincrement,name varchar(128) not null unique,author varchar(128) not null,price double not null);

创建表间关联(也就是通过外键建立关系)

create table groups(id integer primary key autoincrement,name varchar(128) not null unique);crate table users(id integer primary key autoincrement,group_id integer constraint fk_users_group_id references groups(id),username varchar(128) not nullpassword varchar(128) not null);

事务控制

SQLite支持数据库事务

sqlite> begin;sqlite> insert into ……sqlite> commit;sqlite> rollabck;

Android系统中SQLite数据库文件的保存位置

默认情况下,数据库文件保存在如下目录中:

/data/data/<应用程序包>/databases

用户也可以指定将文件保存在任意有权限的目录中,通常SD卡中的目录都可以,在Android系统中连接数据库,使用SQLiteDatabase类连接数据库

SQLiteDatabase  db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);


通过SQLiteOpenHelper类来连接数据库

public class MyHelper extends SQLiteOpenHelper {public static final int VERSION = 1;public static final String DATABASE_NAME = “test.db”;public MyHelper(Context context) {super(context, DATABASE_NAME, null, VERSION);}}


SQLiteDatabase  db = helper.getWritableDatabase();


数据库升级与存在性检测,当应用升级的时候,需要检测数据库是否存在,或者是否要升级,SQLiteOpenHelper提供了创建与升级的能力



public MyHelper(Context context) {super(context, DATABASE_NAME, null, VERSION);}



覆盖onCreate(SQLiteDatabase db)方法,完成创建任务





public void onCreate(SQLiteDatabase db) {String str_sql = "CREATE TABLE " + TABLE_NAME+ "(” + ID                 + " INTEGER PRIMARY KEYAUTOINCREMENT,”+ TEXT + " text);";db.execSQL(str_sql);}



数据库升级与存在性检测,覆盖onUpdate方法,完成升级任务




public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//这里填写数据库升级操作的代码}



合理关闭数据库连接

不再使用或长时间不用时,应关闭数据库连接

程序退出时

程序暂停时

不再需要操作数据库时

使用SQLiteDatabase类中的close方法关闭连接




执行查询(假设已经存在了数据库连接句柄db)

在SQLiteDatabase中提供了如下方法用于查询




execSQL




insert、insertOrThrow、insertWithOnConflict




query、rawQuery




replace、replaceOrThrow




update、updateWithOnConflict




delete





执行查询(假设已经存在了数据库连接句柄db),插入记录示例





//将一条新记录的各个字段内容装入一个ContentValues对象ContentValues cv = new ContentValues();cv.put("name",user.getName());cv.put("age",user.getAge());cv.put("remark",user.getRemark());//插入一条新记录db.insert("users",null, cv);



执行查询(假设已经存在了数据库连接句柄db)

u删除记录示例




//第一个参数为表名//第二个参数表示where后的条件表达式,可以使用?//第三个参数则是一个对应每一个?值的数组db.delete("users", "id=?", new String[]{String.valueOf(userId)});


更新记录示例

ContentValues cv = new ContentValues();cv.put("name", user.getName());cv.put("age", user.getAge());cv.put("remark", user.getRemark());db.update("users", cv, "id=?",new String[]{String.valueOf(userId)});

执行查询(假设已经存在了数据库连接句柄db)

u单表查询所有记录示例

Cursor c = db.query("users", null, null, null, null, null, "name");List<User> users = null;if(c != null) {users = new ArrayList<User>();while(c!=null && c.moveToNext()) {User u = new User();u.setId(c.getInt(0));u.setName(c.getString(1));u.setAge(c.getInt(2));u.setRemark(c.getString(3));users.add(u);}c.close();}




执行查询(假设已经存在了数据库连接句柄db)

单表条件查询记录示例




Cursor c = db.query(“users”,  //表名new String[]{“name”, “age”}, //select包含的字段 “age > ?”,  //where条件表达式new String[]{“10”},  //条件值null,  //group子句null,  //having子句“name desc” //排序字段);




执行查询(假设已经存在了数据库连接句柄db)

任意SQL条件查询记录示例

String sql = “select name, age from users where age > ?”Cursor c = db.query(sqlnew String[]{“10”});


事务是确保数据库操作原子性的保障

SQLiteDatabase提供了如下方法用于事务处理

beginTransaction 开启事务

setTransactionSuccessful 提交事务

endTransaction 关闭事务,如果未提交事务,则自动rollback



db.beginTransaction(); //开始事务try {…… //这里填写数据库操作代码db.setTransactionSuccessful();  //提交事务} finally {db.endTransaction(); //关闭事务}

数据绑定的必要性


数据绑定是指将界面和数据进行绑定,在界面和数据之间建立绑定模式有助于数据的呈现

Adapter其实就是界面和数据之间绑定的桥梁,将视图和数据绑定后将会降低维护数据的复杂度

SimpleCursorAdapter提供了数据层的数据绑定桥梁

SimpleCursorAdapter可以将数据库层的数据提供给列表

1、准备一个列表项的布局用于ListView的展现



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="horizontal" ><TextView android:id="@+id/nametextview“ android:layout_width="0dp“android:layout_height="40dp“ android:layout_weight="1"/><TextView android:id="@+id/agetextview“ android:layout_width="80dp"android:layout_height="40dp"/></LinearLayout>

SimpleCursorAdapter可以将数据库层的数据提供给列表

2、使用SimpleCursorAdapter展现数据 



ListView bookListView = (ListView)findViewById(R.id.booklist);String [] from = new String[] { "_name", "_age“ };int [] to = new int[] { R.id.nametextview, R.id.agetextview };Cursor cursor = db.rawQuery(“select * from books”, null);SimpleCursorAdapter adapter = new         SimpleCursorAdapter(MainActivity.this,                 R.layout.book_list_item, cursor, from, to, 0);bookListView.setAdapter(adapter);


修改绑定数据

有时候直接展现的数据可能不符合要求,需要转变后展示,可以通过SimpleCursorAdapter.ViewBinder接口来实现

修改的步骤如下:

1、编写一个类实现SimpleCursorAdapter.ViewBinder接口

SimpleCursorAdapter.ViewBinder viewBinder = new SimpleCursorAdapter.ViewBinder() {public boolean setViewValue(View view, Cursor cursor, int columnIndex) {if(cursor.getColumnIndex("_name") == columnIndex) {TextView v = (TextView)view;v.setText("N:" + cursor.getString(columnIndex));return true;}return false;}};

修改绑定数据

修改的步骤如下:

2、使用ViewBinder修改数据

ListView bookListView = (ListView)findViewById(R.id.booklist);String [] from = new String[] { "_name", "_age“ };int [] to = new int[] { R.id.nametextview, R.id.agetextview };Cursor cursor = db.rawQuery(“select * from books”, null);SimpleCursorAdapter adapter = new         SimpleCursorAdapter(MainActivity.this,                 R.layout.book_list_item, cursor, from, to, 0);adapter.setViewBinder(viewBinder);bookListView.setAdapter(adapter);


猜你喜欢

转载自blog.51cto.com/2096101/2588808