Android之SQLite数据库

SQLite简介

SQLite是一个开源的嵌入式关系数据库,它在2000年由D.RichardHipp发布,它可以减少应用程序管理数据的开销,SQLite可移植性好、很容易使用、很小、高效而且可靠。目前在Android系统中集成的是SQLite3版本,SQLite不支持静态数据类型,而是使用列关系。这意味着它的数据类型不具有表列属性,而具有数据本身的属性。当某个值插入数据库时,SQLite将检查它的类型。如果该类型与关联的列不匹配,则SQLite会尝试将该值转换成列类型。如果不能转换,则该值将作为其本身具有的类型存储。SQLite支持NULL、INTEGER、REAL、TEXT和BLOB数据类型。例如:可以在Integer字段中存放字符串,或者在布尔型字段中存放浮点数,或者在字符型字段中存放日期型值。但是有一种例外,如果你的主键是INTEGER,那么只能存储64位整数,当向这种字段中保存除整数以外的数据时,将会产生错误。另外,SQLite在解析REATETABLE语句时,会忽略CREATETABLE语句中跟在字段名后面的数据类型信息。

SQLite的特点

SQlite数据库总结起来有五大特点:

1.零配置

SQlite3不用安装、不用配置、不用启动、关闭或者配置数据库实例。当系统崩溃后不用做任何恢复操作,在下次使用数据库的时候自动恢复。

2.可移植

它是运行在Windows、Linux、BSD、MacOSX和一些商用Unix系统,比如Sun的Solaris、IBM的AIX,同样,它也可以工作在许多嵌入式操作系统下,比如Android、QNX、VxWorks、PalmOS、Symbin和WindowsCE。

3.紧凑

SQLite是被设计成轻量级、自包含的。一个头文件、一个lib库,你就可以使用关系数据库了,不用任何启动任何系统进程。

4.简单

SQLite有着简单易用的API接口。

5.可靠

SQLite的源码达到100%分支测试覆盖率。

使用SQLiteOpenHelper抽象类建立数据库

抽象类SQLiteOpenHelper用来对数据库进行版本管理,不是必须使用的。

为了实现对数据库版本进行管理,SQLiteOpenHelper类提供了两个重要的方法,分别onCreate(SQLiteDatabasedb)和onUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion)用于初次使用软件时生成数据库表,后者用于升级软件时更新数据库表结构。

publicSQLiteOpenHelper(Contextcontext,Stringname,

SQLiteDatabase.CursorFactoryfactory,intversion)

Context:代表应用的上下文。

Name:代表数据库的名称。

Factory:代表记录集游标工厂,是专门用来生成记录集游标,记录集游标是对查询结果进行迭代的,后面我们会继续介绍。

Version:代表数据库的版本,如果以后升级软件的时候,需要更改Version版本号,那么onUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion)方法会被调用,在这个方法中比较适合实现软件更新时修改数据库表结构的工作。

实验步骤

1、建立数据库类DatabaseHelper

publicclassDatabaseHelperextendsSQLiteOpenHelper{

staticStringdbName="myAndroid_db.db";

staticintversion=1;

publicDatabaseHelper(Contextcontext){

super(context,dbName,null,version);

}

//第一次使用的时候会被调用,用来建库

publicvoidonCreate(SQLiteDatabasedb){

Stringsql="createtableperson11(personidintegerprimarykey

autoincrement,namevarchar(20),ageinteger)";

db.execSQL(sql);

}

publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,

intnewVersion){

Stringsql="droptableifexistsperson";

onCreate(db);

}

}

2、编写测试类进行测试

publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){

// Stringsql="droptableifexistsperson";

// Log.i("TAG","我被删除了");

// onCreate(db);

Stringsql="altertablepersonaddphonechar(20)null";

db.execSQL(sql);

}

3、数据库更新测试

首先修改版本号version的值(递增)

然后重新运行测试方法testCreateDb()

CRUD

实验步骤

建立PersonService业务类

packagecn.class3g.service;

publicclassPersonService{

privateDatabaseHelperdbHelper;

privateContextcontext;

publicPersonService(Contextcontext){

this.context=context;

dbHelper=newDatabaseHelper(context);

}

publicvoidsave(Personperson){

SQLiteDatabasedb=dbHelper.getWritableDatabase();

//Stringsql="insertintoperson(name,age)values('Tom',21)";

//db.execSQL(sql);

//防止用户输入数据错误,如:name="T'om"

Stringsql="insertintoperson(name,age)values(?,?)";

db.execSQL(sql,newObject[]{person.getName(),person.getAge()});

}

publicvoidupdate(Personperson,intid){

SQLiteDatabasedb=dbHelper.getWritableDatabase();

Stringsql="updatepersonsetname=?,age=?wherepersonid=?";

db.execSQL(sql,newObject[]{person.getName(),person.getAge(),id});

}

publicPersonfind(intid){

SQLiteDatabasedb=dbHelper.getReadableDatabase();

Stringsql="select*frompersonwherepersonid=?";

Cursorcursor=db.rawQuery(sql,newString[]{String.valueOf(id)});

if(cursor.moveToNext()){

Personperson=newPerson();

person.setName(cursor.getString(cursor.getColumnIndex("name")));

person.setId(cursor.getInt(0));

person.setAge(cursor.getInt(2));

cursor.close();//关闭游标

returnperson;

}

returnnull;

}

publicvoiddelete(intid){

SQLiteDatabasedb=dbHelper.getReadableDatabase();

Stringsql="deletefrompersonwherepersonid=?";

db.execSQL(sql,newObject[]{id});

}

publicList<Person>getScrollData(intstartIdx,intcount){

SQLiteDatabasedb=dbHelper.getReadableDatabase();

Stringsql="select*frompersonlimit?,?";

Cursorcursor=db.rawQuery(sql,

newString[]{String.valueOf(startIdx),

String.valueOf(count)});

List<Person>list=newArrayList<Person>();

while(cursor.moveToNext()){

Personp=newPerson();

p.setId(cursor.getInt(0));

p.setName(cursor.getString(1));

p.setAge(cursor.getInt(2));

list.add(p);

}

cursor.close();

returnlist;

}

publiclonggetRecordsCount(){

SQLiteDatabasedb=dbHelper.getReadableDatabase();

Stringsql="selectcount(*)fromperson";

Cursorcursor=db.rawQuery(sql,null);

cursor.moveToFirst();

longcount=cursor.getInt(0);

cursor.close();

returncount;

}

}

在测试类cn.class3g.db.PersonServiceTest中添加对应测试方法

packagecn.class3g.db;

publicclassPersonServiceTestextendsAndroidTestCase{

publicvoidtestSave()throwsThrowable{

PersonServiceservice=newPersonService(this.getContext());

Personperson=newPerson();

person.setName("zhangxiaoxiao");

service.save(person);

Personperson2=newPerson();

person2.setName("laobi");

service.save(person2);

Personperson3=newPerson();

person3.setName("lili");

service.save(person3);

Personperson4=newPerson();

person4.setName("zhaoxiaogang");

service.save(person4);

}

publicvoidtestUpdate()throwsThrowable{

PersonServiceps=newPersonService(this.getContext());

Personperson=newPerson("Ton",122);

ps.update(person,2);//需要实现查看数据库中Tonid

}

publicvoidtestFind()throwsThrowable{

PersonServiceps=newPersonService(this.getContext());

Personperson=ps.find(2);

Log.i("TAG",person.toString());

}

publicvoidtestDelete()throwsThrowable{

PersonServiceps=newPersonService(this.getContext());

ps.delete(2);

}

publicvoidtestScroll()throwsThrowable{

PersonServiceservice=newPersonService(this.getContext());

List<Person>personList=service.getScrollData(3,2);

Log.i("TAG",personList.toString());

}

publicvoidtestCount()throwsThrowable{

PersonServiceservice=newPersonService(this.getContext());

longcount=service.getRecordsCount();

Log.i("TAG",String.valueOf(count));

}

}

常见异常

android.database.sqlite.SQLiteException:Can'tupgraderead-onlydatabasefromversion0to1:

这个错误基本上都是sql有问题导致的,仔细检查sql即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值