---
title: "Android开发之SQLite技术详解"
author: "mywebcode"
date: "2011-12-04T17:08:00Z"
tags: []
slug: "android-sqlite"
draft: false
lastmod: "2013-05-08T10:25:10Z"
id: 1862797
url: "https://mywebcode.iteye.com/blog/1862797"
---

# Android开发之SQLite技术详解

　Google为Andriod的较大的数据处理提供了SQLite，他在数据存储、管理、维护等各方面都相当出色，功能也非常的强大。SQLite具备下列特点：

　　1.轻量级

　　使用 SQLite 只需要带一个动态库，就可以享受它的全部功能，而且那个动态库的尺寸想当小。

　　2.独立性

　　SQLite 数据库的核心引擎不需要依赖第三方软件，也不需要所谓的“安装”。

　　3.隔离性

　　SQLite 数据库中所有的信息(比如表、视图、触发器等)都包含在一个文件夹内，方便管理和维护。

　　4.跨平台

　　SQLite 目前支持大部分[操作系统](http://product.it168.com/list/b/0501_1.shtml "操作系统")，不至电脑[操作系统](http://product.pcpop.com/Operating_System/10734_1.html "操作系统")更在众多的[手机](http://product.it168.com/list/b/0302_1.shtml "手机")系统也是能够运行，比如：Android。

　　5.多语言接口

　　SQLite 数据库支持多语言编程接口。

　　6.安全性

　　SQLite 数据库通过数据库级上的独占性和共享锁来实现独立事务处理。这意味着多个进程可以在同一时间从同一数据库读取数据，但只能有一个可以写入数据。

　　Android中的SQLite使用

　　首先创建数据库类

　　view sourceprint?public class DatabaseHelper extends SQLiteOpenHelper {

　　private static final String DB\_NAME = "mydata.db"; //数据库名称

　　private static final int version = 1; //数据库版本

　　public DatabaseHelper(Context context) {

　　super(context, DB\_NAME, null, version);

　　// TODO Auto-generated constructor stub

　　}

　　@Override

　　public void onCreate(SQLiteDatabase db) {

　　String sql = "create table user(username varchar(20) not null , password varchar(60) not null );";

　　db.execSQL(sql);

　　}

　　@Override

　　public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

　　// TODO Auto-generated method stub

　　}

　　}

　　SQLiteOpenHelper类介绍

　　SQLiteOpenHelper是SQLiteDatabase的一个帮助类，用来管理数据库的创建和版本的更新。一般是建立一个类继承它，并实现它的onCreate和onUpgrade方法。

　　方法名方法描述

　　SQLiteOpenHelper(Context context,String name,SQLiteDatabase.CursorFactory factory,int version)构造方法，一般是传递一个要创建的数据库名称那么参数

　　onCreate(SQLiteDatabase db)创建数据库时调用

　　onUpgrade(SQLiteDatabase db,int oldVersion , int newVersion)版本更新时调用

　　getReadableDatabase()创建或打开一个只读数据库

　　getWritableDatabase()创建或打开一个读写数据库

　　下面来介绍调用的方法

　　创建数据库

　　这里特别的地方是通过调用了SQLiteOpenHelper类的getReadableDatabase()方法来实现创建一个数据库的

　　view sourceprint?1DatabaseHelper database = new DatabaseHelper(this);//这段代码放到Activity类中才用this

　　2SQLiteDatabase db = null;

　　3db = database.getReadalbeDatabase();

　　SQLiteDatabase类为我们提供了很多种方法，而较常用的方法如下

　　(返回值)方法名方法描述

　　(int) delete(String table,String whereClause,String\[] whereArgs)删除数据行的便捷方法

　　(long) insert(String table,String nullColumnHack,ContentValues values)添加数据行的便捷方法

　　(int) update(String table, ContentValues values, String whereClause, String\[] whereArgs)更新数据行的便捷方法

　　(void) execSQL(String sql)执行一个SQL语句，可以是一个select或其他的sql语句

　　(void) close()关闭数据库

　　(Cursor) query(String table, String\[] columns, String selection, String\[] selectionArgs, String groupBy, String having, String orderBy, String limit)查询指定的数据表返回一个带游标的数据集

　　(Cursor) rawQuery(String sql, String\[] selectionArgs)运行一个预置的SQL语句，返回带游标的数据集(与上面的语句最大的区别就是防止SQL注入)

　　数据的添删改查分别可以通过2种途径来实现

　　数据的添加

　　1.使用insert方法

　　view sourceprint?1ContentValues cv = new ContentValues();//实例化一个ContentValues用来装载待插入的数据cv.put("username","Jack Johnson");//添加用户名

　　2cv.put("password","iLovePopMusic"); //添加密码

　　3db.insert("user",null,cv);//执行插入操作

　　2.使用execSQL方式来实现

　　view sourceprint?1String sql = "insert into user(username,password) values ('Jack Johnson','iLovePopMuisc');//插入操作的SQL语句

　　2db.execSQL(sql);//执行SQL语句

　　数据的删除

　　同样有2种方式可以实现

　　view sourceprint?1String whereClause = "username=?";//删除的条件

　　2String\[] whereArgs = {"Jack Johnson"};//删除的条件参数

　　3db.delete("user",whereClause,whereArgs);//执行删除

　　使用execSQL方式的实现

　　view sourceprint?1String sql = "delete from user where username='Jack Johnson'";//删除操作的SQL语句

　　2db.execSQL(sql);//执行删除操作

　　数据修改

　　同上，仍是2种方式

　　view sourceprint?1ContentValues cv = new ContentValues();//实例化ContentValues

　　2cv.put("password","iHatePopMusic");//添加要更改的字段及内容

　　3String whereClause = "username=?";//修改条件

　　4String\[] whereArgs = {"Jack Johnson"};//修改条件的参数

　　5db.update("user",cv,whereClause,whereArgs);//执行修改

　　使用execSQL方式的实现

　　view sourceprint?1String sql = "update \[user] set password = 'iHatePopMusic' where username='Jack Johnson'";//修改的SQL语句

　　2db.execSQL(sql);//执行修改

　　数据查询

　　数据查询相对前面几种方法就复杂一些了，因为查询会带有很多条件

　　通过query实现查询的

　　public Cursor query(String table, String\[] columns, String selection, String\[] selectionArgs, String groupBy, String having, String orderBy, String limit)

　　各参数说明：

　　table：表名称

　　colums：列名称数组

　　selection：条件子句，相当于where

　　selectionArgs：条件语句的参数数组

　　groupBy：分组

　　having：分组条件

　　orderBy：排序类

　　limit：分页查询的限制

　　Cursor：返回值，相当于结果集ResultSet

　　针对游标(Cursor)也提供了不少方法

　　方法名称方法描述

　　getCount()总记录条数

　　isFirst()判断是否第一条记录

　　isLast()判断是否最后一条记录

　　moveToFirst()移动到第一条记录

　　moveToLast()移动到最后一条记录

　　move(int offset)移动到指定的记录

　　moveToNext()移动到吓一条记录

　　moveToPrevious()移动到上一条记录

　　getColumnIndex(String columnName)获得指定列索引的int类型值

　　实现代码

Cursor c = db.query("user",null,null,null,null,null,null);//查询并获得游标  
if(c.moveToFirst()){//判断游标是否为空  
for(int i=0;i&lt;c.getCount();i++){  
c.move(i);//移动到指定记录  
String username = c.getString(c.getColumnIndex("username");  
String password = c.getString(c.getColumnIndex("password"));  
}  
}

通过rawQuery实现的带参数查询

Cursor c = db.rawQuery("select * from user where username=?",new Stirng\[]{"Jack Johnson"});  
if(cursor.moveToFirst()) {  
String password = c.getString(c.getColumnIndex("password"));  
}