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本身是一个很小型的数据库, ...
随机推荐
- 基于Hadoop的大数据平台实施记——整体架构设计[转]
http://blog.csdn.net/jacktan/article/details/9200979 大数据的热度在持续的升温,继云计算之后大数据成为又一大众所追捧的新星.我们暂不去讨论大数据到底 ...
- traceroute原理
traceroute原理 ICMP ICMP全称为Internet Control Message Protocol,即,网络控制报文协议. 当一个IP数据报发送失败时,最后一个路由器会向发送发传递一 ...
- asp.net服务器向客户端弹出对话框,但不使页面边白板
1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Web; 5: ...
- Javascript基础Function
函数声明与表达式 function someFunc(){ alert("这是一个函数"); } var func=function(){ alert("函数表达式&qu ...
- oracle学习笔记(一)用户管理
--oracle学习第一天 --连接 @后面连接数据库实例,具体连接到那个数据库 conn scott/tiger@MYORA1; --修改密码 passw; --显示用户 show user; -- ...
- C++中的类指针
代码: #include <iostream> #include <string> #include <cstdio> using namespace std; c ...
- Render和template?
Template是一个模板. render = web.template.render('templates/') 这会告诉web.py到你的模板目录中去查找模板.然后把 index.GET改成: 告 ...
- OpenRisc-39-ORPSoC,or1200的memory hierarchy整体分析
引言 前面我们简单分析了ORPSoC的整体结构,or1200_top的整体结构,or1200_cpu的整体结构. 并对ORPSoC的启动过程,ORPSoC的debug子系统,clock子系统进行了介绍 ...
- SharpZipLib 压缩文档下载
using ICSharpCode.SharpZipLib.Zip; Response.Clear(); Response.ClearContent(); Response.ClearHeaders( ...
- Js与Jq 获取浏览器和对象值的方法
JS and Jquery 都能获取页面元素的宽度,高度和相对位移等数值,那他们之间能相互转换或替代吗,写法又有哪些差异呢?本文将详细为你介绍. 1.Js获取浏览器高度和宽度document.docu ...