android中SQLite的使用,其实倒也不难,但是与JDBC操作数据库相比,这个还是有点不顺手,而且我好久没写底层的封装了,使用SSM框架这些都不需要考虑......好了,废话不多说,下面直接建立一个测试工程来试试SQLite在Android中的应用吧。


1、新建一个工程




2、配置junit测试环境

打开AndroidManifest.xml文件,进行jUnit相关配置,具体如下图:



3、源码

关于在Android中如何使用SQLite的文章很多,我也是参考那些文章进行学习的。作为一个J2EE方向的开发者,我习惯于面向对象进行编程,而老罗的视频以及一些其他的教程关于CRUD操作使用的都是字符串,这我有点不适应,所有我在学习的过程中就改成了面向对象的CRUD操作,这样用着也方便点。原理、API什么的我就不说了,百度一下嗖嗖的都出来了,下面直接贴代码(完整工程下载,点这里):

这样一个继承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会被调用@Overridepublic 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@Overridepublic 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;}@Overridepublic 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);}@Overridepublic 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;}@Overridepublic 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;}@Overridepublic 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;}@Overridepublic 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)

更多相关文章

  1. 在Android中使用Handler和Thread线程执行后台操作
  2. 【Android开发 .9图的使用】Android(安卓)Studio中关于.9.png图
  3. 按着步骤来,学习Android(安卓)NDK入门很简单
  4. Android中Activity之间的数据传递和Intent使用
  5. android 中 EditText使用技巧汇总
  6. 在Android中使用Handler和Thread线程执行后台操作
  7. 箭头函数的基础使用
  8. NPM 和webpack 的基础使用
  9. Python list sort方法的具体使用

随机推荐

  1. Android SDK Manager 无法更新下载怎么办
  2. Android SDK更新 Connection to http://d
  3. Android APK权限大全
  4. android 让Activity单例运行
  5. Android 日期控件的简单实现
  6. Android NDK Overview ---- Android 4.4
  7. Android 给TextView 添加图片(左右等)
  8. android通过http上传图片
  9. Android HandlerThread使用
  10. Android,visibility属性