Android为SQLite数据库提供了全面的支持,创建的任何数据库都会被App内部的类访问到。(不是外部)

The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method, in which you can execute a SQLite command to create tables in the database. For example:



使用一个新的SQLite数据库的方法是创建一个SQLiteOpenHelper的子类,并且重写onCreate方法,在这里面你可以执行一个SQLite命令在数据库中创建一张表。


You can then get an instance of your SQLiteOpenHelper implementation using the constructor you've defined. To write to and read from the database, call getWritableDatabase() and getReadableDatabase(), respectively. These both return a SQLiteDatabase object that represents the database and provides methods for SQLite operations.

你可以得到一个你定义的SQLiteOpenHelper子类的实例,为了读写数据库,你可以调用getWritableDatabase()或者getReadableDatabase()来得到一个SQLiteDatabase对象的实例,这个对象代表了数据库,并且提供了操纵SQLite的方法。


首先实现SQLiteOpenHelper的子类:

package com.example.android_db.db;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;public class DBOpenHelper extends SQLiteOpenHelper {private static String name = "mydb.db"; // 表示数据库的名称private static int version = 2; // 数据库的版本号码public DBOpenHelper(Context context) {super(context, name, null, version);// 这里没有真正创建数据库}// 当数据库创建的时候,是第一次被执行,完成对数据库表的创建//数据库不存在的时候则创建@Overridepublic void onCreate(SQLiteDatabase db) {// TODO Auto-generated method stub//支持的数据类型 整型  字符串 日期类型 二进制数据类型String sql = "create table person(id integer primary key autoincrement, name varchar(64),address varchar(64))";db.execSQL(sql);}//数据库版本不一致则升级,不会再去执行onCreate方法@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stubString sql = "alter table person add sex varchar(8)";db.execSQL(sql);}}

在后台,如果数据库不存在,那么执行onCreate创建数据库,如果版本号不一致,那么执行onUpgrade进行升级。

这里注意:SQLIteHelper将数据库实力的创建和打开操作延迟到了第一次需要他们时,并在成功打开数据库实例后缓存他们。


对于数据库的操作有两种方式:

一 自己编写SQL语句,例如插入一条记录:

@Overridepublic boolean addPerson(Object[] params) {// TODO Auto-generated method stubboolean flag = false;//实现对数据库的CRUDSQLiteDatabase database = null;try {String sql = "insert into person(name,address,sex) values(?,?,?)";database = helper.getWritableDatabase(); //实现对数据库写的操作database.execSQL(sql, params);flag = true;} catch (Exception e) {// TODO: handle exception}finally{if (database != null){database.close();}}return flag;}

另外一种是调用insert delete update query等函数:

package com.example.android_db.dao;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import com.example.android_db.db.DBOpenHelper;import com.example.android_db.service.PersonService2;public class PersonDao2 implements PersonService2 {private DBOpenHelper helper = null;public PersonDao2(Context context) {// TODO Auto-generated constructor stubhelper = new DBOpenHelper(context);}@Overridepublic boolean addPerson(ContentValues values) {// TODO Auto-generated method stubboolean flag = false;SQLiteDatabase database = null;long id = -1;try {database = helper.getWritableDatabase();id = database.insert("person", null, values);flag = (id != -1);} catch (Exception e) {// TODO: handle exception} finally {if (database != null) {database.close();}}return flag;}@Overridepublic boolean deletePerson(String whereClause, String[] whereArgs) {// TODO Auto-generated method stubboolean flag = false;SQLiteDatabase database = null;int count = 0;try {database = helper.getWritableDatabase();count = database.delete("person", whereClause, whereArgs);flag = (count > 0);} catch (Exception e) {// TODO: handle exception} finally {if (database != null) {database.close();}}return flag;}@Overridepublic boolean updatePerson(ContentValues values, String whereClause,String[] whereArgs) {// TODO Auto-generated method stubboolean flag = false;SQLiteDatabase database = null;int count = 0; // 影响数据库的行数try {database = helper.getWritableDatabase();count = database.update("person", values, whereClause, whereArgs);flag = (count > 0);} catch (Exception e) {// TODO: handle exception} finally {if (database != null) {database.close();}}return flag;}@Overridepublic Map<String, String> viewPerson(String selection,String[] selectionArgs) {// TODO Auto-generated method stub// select 列的名称 fromMap<String, String> map = new HashMap<String, String>();SQLiteDatabase database = null;Cursor cursor = null;try {database = helper.getReadableDatabase();cursor = database.query(true, "person", null, selection,selectionArgs, null, null, null, null);int cols_len = cursor.getColumnCount();while (cursor.moveToNext()) {for (int i = 0; i < cols_len; i++) {String cols_name = cursor.getColumnName(i);String cols_value = cursor.getString(cursor.getColumnIndex(cols_name));if (cols_value == null) {cols_value = "";}map.put(cols_name, cols_value);}}} catch (Exception e) {// TODO: handle exception} finally {if (database != null) {database.close();}}return map;}@Overridepublic List<Map<String, String>> listPersonMaps(String selection,String[] selectionArgs) {// TODO Auto-generated method stubList<Map<String, String>> list = new ArrayList<Map<String, String>>();SQLiteDatabase database = null;Cursor cursor = null;try {database = helper.getReadableDatabase();cursor = database.query(false, "person", null, selection,selectionArgs, null, null, null, null);int cols_len = cursor.getColumnCount();while(cursor.moveToNext()){Map<String, String> map = new HashMap<String, String>();for (int i = 0; i < cols_len; i++) {String cols_name = cursor.getColumnName(i);String cols_value = cursor.getString(cursor.getColumnIndex(cols_name));if (cols_value == null){cols_value = "";}map.put(cols_name, cols_value);}list.add(map);}} catch (Exception e) {// TODO: handle exception} finally {if (database != null) {database.close();}}return list;}}

可以在单元测试中试验是否成功

更多相关文章

  1. Android数据库组件Room
  2. 在android获取root权限的方法^_^。
  3. Android CheckBox控件使用OnClickListener和OnCheckedChangeList
  4. Android Studio安装app 报错的问题It is possible that this iss
  5. Android数据库操作的两种方式
  6. Google Maps API Key申请方法及地址
  7. android 笔记 --- Android Bitmap 建立或取得的方法
  8. Android自带Music播放器更新播放时间和进度条的方法
  9. android使用ant编译找不到apkbuilder.jar的错误的解决方法

随机推荐

  1. Android(安卓)电子罗盘开发
  2. Android中BuildConfig类的那些事
  3. Android开发 常用控件罕见特殊属性集锦
  4. Activity与Service是否处于同一进程
  5. android照相功能介绍
  6. Android activity的DecorView的层次结构
  7. 读取local.properties文件
  8. Android(安卓)中使用Protocol Buffer
  9. Android中应用程序如何获得系统签名权限
  10. Android OS的扩展库支持