您的位置:首页 > 数据库

使用嵌入式关系型SQLite数据库存储数据之使用SQLiteDatabase操作SQLite数据库

2013-06-03 19:36 831 查看
Android提供了一个名为SQLiteDatabase的类,该类封装了一些操作数据库的API,使用该类可以完成对数据进行添加(Create)、查询(Retrieve)、更新(Update)和删除(Delete)操作(这些操作简称为CRUD)。对SQLiteDatabase的学习,我们应该重点掌握execSQL()和rawQuery()方法。 execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句;
rawQuery()方法可以执行select语句。

execSQL()方法的使用例子:

SQLiteDatabase db = ....;

db.execSQL("insert into person(name, age) values('CSDN', 4)");

db.close();

执行上面SQL语句会往person表中添加进一条记录,在实际应用中, 语句中的“传智播客”这些参数值会由用户输入界面提供,如果把用户输入的内容原样组拼到上面的insert语句, 当用户输入的内容含有单引号时,组拼出来的SQL语句就会存在语法错误。要解决这个问题需要对单引号进行转义,也就是把单引号转换成两个单引号。有些时候用户往往还会输入像“ & ”这些特殊SQL符号,为保证组拼好的SQL语句语法正确,必须对SQL语句中的这些特殊SQL符号都进行转义,显然,对每条SQL语句都做这样的处理工作是比较烦琐的。 SQLiteDatabase类提供了一个重载后的execSQL(String
sql, Object[] bindArgs)方法,使用这个方法可以解决前面提到的问题,因为这个方法支持使用占位符参数(?)。使用例子如下:

SQLiteDatabase db = ....;

db.execSQL("insert into person(name, age) values(?,?)", new Object[]{"CSDN", 4});

db.close();

execSQL(String sql, Object[] bindArgs)方法的第一个参数为SQL语句,第二个参数为SQL语句中占位符参数的值,参数值在数组中的顺序要和占位符的位置对应

除了前面给大家介绍的execSQL()和rawQuery()方法, SQLiteDatabase还专门提供了对应于添加、删除、更新、查询的操作方法: insert()、delete()、update()和query() 。这些方法实际上是给那些不太了解SQL语法的菜鸟使用的,对于熟悉SQL语法的程序员而言,直接使用execSQL()和rawQuery()方法执行SQL语句就能完成数据的添加、删除、更新、查询操作。

Insert()方法用于添加数据,各个字段的数据使用ContentValues进行存放。 ContentValues类似于MAP,相对于MAP,它提供了存取数据对应的put(String key, Xxx value)和getAsXxx(String key)方法, key为字段名称,value为字段值,Xxx指的是各种常用的数据类型,如:String、Integer等。

SQLiteDatabase db = databaseHelper.getWritableDatabase();

ContentValues values = new ContentValues();

values.put("name", "csdn");

values.put("age", 4);

long rowid = db.insert(“person”, null, values);//返回新添记录的行号,与主键id无关

不管第三个参数是否包含数据,执行Insert()方法必然会添加一条记录,如果第三个参数为空,会添加一条除主键之外其他字段值为Null的记录。Insert()方法内部实际上通过构造insert语句完成数据的添加,Insert()方法的第二个参数用于指定空值字段的名称,相信大家对此参数会感到疑惑,此参数的作用是干嘛的?是这样的:如果第三个参数values 为Null或者元素个数为0, Insert()方法必然要添加一条除了主键之外其它字段为Null值的记录,为了满足这条insert语句的语法, insert语句必须给定一个字段名,如:insert
into person(name) values(NULL),倘若不给定字段名 , insert语句就成了这样: insert into person() values(),显然这不满足标准SQL的语法。对于字段名,建议使用主键之外的字段,如果使用了INTEGER类型的主键字段,执行类似insert into person(personid) values(NULL)的insert语句后,该主键字段值也不会为NULL。如果第三个参数values 不为Null并且元素的个数大于0 ,可以把第二个参数设置为null。

delete()方法的使用:

SQLiteDatabase db = databaseHelper.getWritableDatabase();

db.delete("person", "personid<?", new String[]{"2"});

db.close();

上面代码用于从person表中删除personid小于2的记录。

update()方法的使用:

SQLiteDatabase db = databaseHelper.getWritableDatabase();

ContentValues values = new ContentValues();

values.put(“name”, “csdn”);//key为字段名,value为值

db.update("person", values, "personid=?", new String[]{"1"});

db.close();

上面代码用于把person表中personid等于1的记录的name字段的值改为“传智播客”。

query()方法实际上是把select语句拆分成了若干个组成部分,然后作为方法的输入参数:

SQLiteDatabase db = databaseHelper.getWritableDatabase();

Cursor cursor = db.query("person", new String[]{"personid,name,age"}, "name like ?", new String[]{"%cs%"}, null, null, "personid desc", "1,2");

while (cursor.moveToNext()) {

int personid = cursor.getInt(0); //获取第一列的值,第一列的索引从0开始

String name = cursor.getString(1);//获取第二列的值

int age = cursor.getInt(2);//获取第三列的值

}

cursor.close();

db.close();

上面代码用于从person表中查找name字段含有“传智”的记录,匹配的记录按personid降序排序,对排序后的结果略过第一条记录,只获取2条记录。

query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit)方法各参数的含义:

table:表名。相当于select语句from关键字后面的部分。如果是多表联合查询,可以用逗号将两个表名分开。

columns:要查询出来的列名。相当于select语句select关键字后面的部分。

selection:查询条件子句,相当于select语句where关键字后面的部分,在条件子句允许使用占位符“?”

selectionArgs:对应于selection语句中占位符的值,值在数组中的位置与占位符在语句中的位置必须一致,否则就会有异常。

groupBy:相当于select语句group by关键字后面的部分

having:相当于select语句having关键字后面的部分

orderBy:相当于select语句order by关键字后面的部分,如:personid desc, age asc;

limit:指定偏移量和获取的记录数,相当于select语句limit关键字后面的部分。

代码示例:

1、写一个DBSQLiteHelper类继承SQLiteOpenHelper

package com.example.lession05_dbs.dbs;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBSQLiteHelper extends SQLiteOpenHelper {

private static final String tag="DBSQLiteHelper";

private static final String name="csdn.db";
private static final int version=1;

public DBSQLiteHelper(Context context) {
super(context, name, null, version);
Log.v(tag, "构造器");
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table person(id integer primary key autoincrement,name varchar(20),age integer)");
Log.v(tag, "数据库创建执行一次");

}

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

}

}


2、根据创建的表写一个实体bean

package com.example.lession05_dbs.domain;

import java.io.Serializable;

public class Person implements Serializable{

/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(Integer id, String name, Integer age) {
super();
this.id = id;
this.name = name;
this.age = age;
}

}


3、写一个接口,里面有增删改查的方法

package com.example.lession05_dbs.dao;

import java.util.List;

import com.example.lession05_dbs.domain.Person;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;

public interface PersonDao {

//添加的操作
public boolean insert(SQLiteDatabase db,ContentValues values);
//执行更新的操作
public boolean update(SQLiteDatabase db,ContentValues values,Integer id);
//根据id删除操作
public boolean delete(SQLiteDatabase db,Integer id);
//查询所有
public List<Person> findAll(SQLiteDatabase db);
//条件查询操作
public List<Person> findByName(SQLiteDatabase db,String[] selectionArgs);
//获取当前页的信息
public List<Person> getNowPageInfo(SQLiteDatabase db,String[] selectionArgs,String order,String limit);
}


4、写一个实现类实现该接口

package com.example.lession05_dbs.dao;

import java.util.ArrayList;
import java.util.List;

import com.example.lession05_dbs.domain.Person;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class PersonDaoImpl implements PersonDao {

@Override
public boolean insert(SQLiteDatabase db, ContentValues values) {
boolean flag=false;
if(db.isOpen()){
long l=db.insert("person",null, values);

/**
* table 表名 nullColumnHack: insert into
* person(name,phone)values('chenhj','123'); //insert into
* person(name) values(null); //insert into person() values();
* values 参数
*
*/
if(l>0){
flag=true;
}
db.close();
}
return flag;
}

@Override
public boolean update(SQLiteDatabase db, ContentValues values, Integer id) {
boolean flag=false;
if(db.isOpen()){
long l=db.update("person", values, "id=?", new String[]{id+""});
if(l>0){
flag=true;
}
db.close();
}
return flag;
}

@Override
public boolean delete(SQLiteDatabase db, Integer id) {
boolean flag=false;
if(db.isOpen()){
long l=db.delete("person", "id=?", new String[]{id+""});
if(l>0){
flag=true;
}
}
return flag;
}

@Override
public List<Person> findAll(SQLiteDatabase db) {
List<Person> persons=new ArrayList<Person>();
if(db.isOpen()){
Cursor cursor=db.query("person", new String[] { "id", "name",
"age" }, null, null, null, null, null);

while(cursor.moveToNext()){
Person person=new Person();

person.setId(cursor.getInt(cursor.getColumnIndex("id")));
person.setName(cursor.getString(cursor.getColumnIndex("name")));
person.setAge(cursor.getInt(cursor.getColumnIndex("age")));

persons.add(person);
}
}
return persons;
}

@Override
public List<Person> findByName(SQLiteDatabase db, String[] selectionArgs) {
List<Person> persons=new ArrayList<Person>();
if (db.isOpen()) {
// 执行查询
Cursor cursor = db.query("person", new String[] { "id", "name","age" }, "name like ?", selectionArgs, null, null, "id desc");

while (cursor.moveToNext()) {
// 创建person对象
Person person = new Person();
// 设置person的属性
person.setId(cursor.getInt(cursor.getColumnIndex("id")));
person.setName(cursor.getString(cursor.getColumnIndex("name")));
person.setAge(cursor.getInt(cursor.getColumnIndex("age")));
// 添加到集合众
persons.add(person);
}
}

return persons;
}

@Override
public List<Person> getNowPageInfo(SQLiteDatabase db,
String[] selectionArgs, String order, String limit) {

List<Person> persons = new ArrayList<Person>();

if (db.isOpen()) {
// 执行查询
Cursor cursor = db.query("person", new String[] { "id", "name","age" }, "name like ?", selectionArgs, null, null, order,limit);

while (cursor.moveToNext()) {
// 创建person对象
Person person = new Person();
// 设置person的属性
person.setId(cursor.getInt(cursor.getColumnIndex("id")));
person.setName(cursor.getString(cursor.getColumnIndex("name")));
person.setAge(cursor.getInt(cursor.getColumnIndex("age")));
// 添加到集合众
persons.add(person);
}
}

return persons;
}

}


5、写一个测试类

首先在项目清单中添加

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lession05_dbs"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<instrumentation android:targetPackage="com.example.lession05_dbs" android:name="android.test.InstrumentationTestRunner"></instrumentation>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.lession05_dbs.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:name="android.test.runner"/>
</application>

</manifest>


其次写代码进行测试

package com.example.lession05_dbs.test;

import java.util.List;

import com.example.lession05_dbs.dao.PersonDao;
import com.example.lession05_dbs.dao.PersonDaoImpl;
import com.example.lession05_dbs.dbs.DBSQLiteHelper;
import com.example.lession05_dbs.domain.Person;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.test.AndroidTestCase;

public class DBTest extends AndroidTestCase{

PersonDao personDao=new PersonDaoImpl();

public void createDB(){
DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
SQLiteDatabase sdb=db.getWritableDatabase();
}

public void insert(){
DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
for(int i=1;i<10;i++){
SQLiteDatabase sdb=db.getWritableDatabase();

ContentValues values=new ContentValues();
Person person=new Person(null, "shuang"+i, 21);

values.put("name", person.getName());
values.put("age",person.getAge());

personDao.insert(sdb, values);
}
}

public void update(){
DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
SQLiteDatabase sdb=db.getWritableDatabase();

ContentValues values=new ContentValues();
Person person=new Person(1,"xue",22);

values.put("name", person.getName());
values.put("age", person.getAge());

personDao.update(sdb, values, person.getId());
}

public void delete(){
DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
SQLiteDatabase sdb=db.getWritableDatabase();
Person person=new Person(1,"xue",22);
personDao.delete(sdb, person.getId());
}

public void findAll(){
DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
SQLiteDatabase sdb=db.getWritableDatabase();

List<Person> persons=personDao.findAll(sdb);
for(Person p:persons){
System.out.println(p.toString());
}
}

public void findByName(){
DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
SQLiteDatabase sdb=db.getWritableDatabase();

List<Person> persons=personDao.findByName(sdb, new String[]{"%g1%"});
for(Person p:persons){
System.out.println(p.toString());
}
}

public void getPage(){
DBSQLiteHelper db=new DBSQLiteHelper(this.getContext());
SQLiteDatabase sdb=db.getWritableDatabase();

List<Person> persons=personDao.getNowPageInfo(sdb, new String[]{"%sh%"}, " id desc ", "0,3");
for(Person p:persons){
System.out.println(p.toString());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: