Android——SQLite实现面向对象CRUD
android中SQLite的使用,事实上倒也不难。可是与JDBC操作数据库相比,这个还是有点不顺手,并且我好久没写底层的封装了,使用SSM框架这些都不须要考虑......好了,废话不多说。以下直接建立一个測试project来试试SQLite在Android中的应用吧。
1、新建一个project
2、配置junit測试环境
打开AndroidManifest.xml文件,进行jUnit相关配置,详细例如以下图:
3、源代码
关于在Android中怎样使用SQLite的文章非常多,我也是參考那些文章进行学习的。
作为一个J2EE方向的开发人员,我习惯于面向对象进行编程,而老罗的视频以及一些其它的教程关于CRUD操作使用的都是字符串,这我有点不适应,全部我在学习的过程中就改成了面向对象的CRUD操作。这样用着也方便点。原理、API什么的我就不说了。百度一下嗖嗖的都出来了,以下直接贴代码(完整project下载。点这里):
这样一个继承SQLiteOpenHelper的类主要就这么几个功能:
a.创建数据库和表
b.假设数据库有不同版本号那么就会更新数据库
c.调用的这个类的对象来取得数据库的读写权限
package com.example.db; import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "test.db";
private static final int DATABASE_VERSION = 1; public DBHelper(Context context) {
// CursorFactory设置为null,使用默认值
super(context, DATABASE_NAME, null, DATABASE_VERSION);
} // 数据库第一次被创建时onCreate会被调用
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS person "
+ "(id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(32),sex VARCHAR(8))";
db.execSQL(sql);
} // 假设DATABASE_VERSION值被改为2,系统发现现有数据库版本号不同,即会调用onUpgrade
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("ALTER TABLE base_info ADD COLUMN other STRING");
}
}
能够看到上面创建了一个叫test.db的数据库。当中有一个表person,表中有三个字段:主键-id。姓名-name,性别-sex。
以下生成这个表相应的实体类:
package com.example.pojo;
public class Person {
private int id;
private String name;
private String sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", sex=" + sex + "]";
}
}
我们要实现CRUD操作,那么建一个接口定义CRUD方法:
package com.example.dao;
import com.example.pojo.Person;
public interface IPersonDao {
public boolean insert(Person person);
public boolean delete(int id);
public boolean update(Person person);
public Person select(int id);
}
以下要实现IPersonDao接口。定义详细的业务方法:
package com.example.dao.impl; import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import com.example.dao.IPersonDao;
import com.example.db.DBHelper;
import com.example.pojo.Person; public class PersonDaoImpl implements IPersonDao {
DBHelper helper = null; public PersonDaoImpl(Context context){
helper = new DBHelper(context);
} @Override
public boolean insert(Person person) {
boolean flag = false;
SQLiteDatabase database = null;
try {
String sql = "INSERT INTO person(name,sex) VALUES (?,?)";
database = helper.getWritableDatabase();
database.execSQL(sql, new Object[]{person.getName(),person.getSex()});
flag = true;
} catch (Exception e) {
e.printStackTrace();
}finally{
if(database!=null){
database.close();
}
}
return flag;
} @Override
public boolean delete(int id) {
boolean flag = false;
SQLiteDatabase database = null;
try {
String sql = "DELETE FROM person WHERE id=?";
database = helper.getWritableDatabase();
database.execSQL(sql, new Object[]{Integer.toString(id)});
flag = true;
} catch (Exception e) {
e.printStackTrace();
}finally{
if(database!=null){
database.close();
}
}
return flag;
} @Override
public boolean update(Person person) {
boolean flag = false;
SQLiteDatabase database = null;
try {
String sql = "UPDATE person set name=? , sex=? where id=?";
database = helper.getWritableDatabase();
database.execSQL(sql, new Object[]{person.getName(),person.getSex(),person.getId()});
flag = true;
} catch (Exception e) {
e.printStackTrace();
}finally{
if(database!=null){
database.close();
}
}
return flag;
} @Override
public Person select(int id) {
Person person = new Person();
SQLiteDatabase database = null;
try {
String sql = "SELECT * FROM person where id=?";
database = helper.getReadableDatabase();
Cursor cursor = database.rawQuery(sql, new String[]{Integer.toString(id)});
while(cursor.moveToNext()){
int _id = cursor.getInt(cursor.getColumnIndex("id"));
String _name = cursor.getString(cursor.getColumnIndex("name"));
String _sex = cursor.getString(cursor.getColumnIndex("sex"));
person.setId(_id);
person.setName(_name);
person.setSex(_sex);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(database!=null){
database.close();
}
}
return person;
} }
以上完毕之后就能够開始单元測试了。绿色......
package com.example.test; import com.example.dao.IPersonDao;
import com.example.dao.impl.PersonDaoImpl;
import com.example.pojo.Person; import android.test.AndroidTestCase;
import android.util.Log; public class Test extends AndroidTestCase {
public void insertDB(){
IPersonDao personDao = new PersonDaoImpl(getContext());
Person person = new Person();
person.setName("李四");
person.setSex("男");
personDao.insert(person);
} public void selectDB(){
IPersonDao personDao = new PersonDaoImpl(getContext());
Person person = personDao.select(1);
Log.i("info", person.toString());
} public void updateDB(){
IPersonDao personDao = new PersonDaoImpl(getContext());
Person person = personDao.select(1);
person.setName("改名字啦");
person.setSex("不详");
personDao.update(person);
} public void deleteDB(){
IPersonDao personDao = new PersonDaoImpl(getContext());
personDao.delete(2);
} }
导出test.db文件。在SQLite Expert中打开:
这是insert測试成功的样例。其它就不放图了,这个软件百度就能够下载了。
(转载注明出处:http://blog.csdn.net/zhshulin)
Android——SQLite实现面向对象CRUD的更多相关文章
- Android SQLite 数据库 增删改查操作
Android SQLite 数据库 增删改查操作 转载▼ 一.使用嵌入式关系型SQLite数据库存储数据 在Android平台上,集成了一个嵌入式关系型数据库--SQLite,SQLite3支持NU ...
- Android SQLite 简易指北
Android SQLite SQLite一款开源的, 轻量级的数据库. 以文本文件的形式存储数据. SQLite支持所有标准的关系型数据库特性. SQLite运行时占用内存非常少(约250 KByt ...
- Android SQLite 通配符查询找不到参数问题
使用Android SQLite中SQLiteDatabase类的query方法查询时,如果where中包含通配符,则参数会无法设置,如类似下面的方法查询时 SQLiteDatabase db = d ...
- Android+Sqlite 实现古诗阅读应用(三)
往期传送门: Android+Sqlite 实现古诗阅读应用(一) Android+Sqlite 实现古诗阅读应用(二) 加入截图分享的功能. 很多应用都有分享的功能,我也想在我的古诗App里加入这个 ...
- Android+Sqlite 实现古诗阅读应用(二)
传送门:Android+Sqlite 实现古诗阅读应用(一) Hi,又回来了,最近接到很多热情洋溢的小伙伴们的来信,吼开心哈,我会继续努力的=-=! 上回的东西我们做到了有个textview能随机选择 ...
- Android Sqlite 数据库版本更新
Android Sqlite 数据库版本更新 http://87426628.blog.163.com/blog/static/6069361820131069485844/ 1.自己写一个类继承 ...
- Android SQLite总结(一) (转)
Android SQLite总结(一) 郑海波 2012-08-21 转载请声明:http://blog.csdn.net/nuptboyzhb/article/details/7891887 前言 ...
- android SQLite使用SQLiteOpenHelper类对数据库进行操作
android SQLite使用SQLiteOpenHelper类对数据库进行操作 原文: http://byandby.iteye.com/blog/835580
- Android sqlite管理数据库基本用法
Android操作系统中内置了sqlite数据库(有关sqlite数据库详细介绍见:http://zh.wikipedia.org/wiki/SQLite),而sqllite本身是一个很小型的数据库, ...
随机推荐
- NSLog用法,打印日志
要输出的格式化占位: %@ 对象 %d, %i 整数 %u 无符整形 %f 浮点/双字 %x, %X 二进制整数 %o 八进制整数 %zu size_t %p 指针 %e 浮点/双字 (科 ...
- HeadFirst设计模式 之 C++实现(二):Observer(观察者模式)
观察者模式是最经常使用的设计模式之中的一个,[对象之间多对一的依赖关系,当一个对象发生变化时,其会通知全部依赖它的对象].拿订阅报纸和发行报社打例如,报社採集到news制作新的报纸,派送给订阅的客户. ...
- stat(),lstat(),fstat() 获取文件/目录的相关信息
stat 的使用 Linux有个命令,ls -l,效果如下: 这个命令能显示文件的类型.操作权限.硬链接数量.属主.所属组.大小.修改时间.文件名.它是怎么获得这些信息的呢,请看下面的讲解. stat ...
- Merge Sorted Array 合并数组并排序
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note:Yo ...
- ubuntu14.04中解压缩window中的zip文件,文件名乱码的解决方法
在windows上压缩的文件,是以系统默认编码中文来压缩文件.由于zip文件中没有声明其编码,所以linux上的unzip一般以默认编码解压,中文文件名会出现乱码. 通过unzip行命令解压,指定字符 ...
- js判断上传文件的类型和大小
//检测文件大小和类型 function fileChange(target){ //检测上传文件的类型 if(!(/(?:jpg|gif|png|jpeg)$/i.test(target.value ...
- [转]Hibernate映射的基本操作
++YONG原创,转载请注明http://blog.csdn.net/qjyong/article/details/1829672 Hibernate映射主要是通过对象关系映射 ...
- CSS3学习之圆角box-shadow,阴影border-radius
最近经常玩腾讯微博,出来职业习惯,看看它的CSS,里面运用了大量的css3的东东,有一处用到了Data URI,还有css expression有争议的地方,对png24图片的处理也是用滤镜,类似( ...
- CSS3属性之一:border-radius
语法: border-radius : none | <length>{1,4} [ / <length>{1,4} ]? 相关属性: border-top-right-rad ...
- 函数:我的地盘听我的 - 零基础入门学习Python019
函数:我的地盘听我的 让编程改变世界 Change the world by program 函数与过程 在小甲鱼另一个实践性超强的编程视频教学<零基础入门学习Delphi>中,我们谈到了 ...