Android SQLite使用
2016-04-28 00:00
459 查看
一、Cursor的使用
使用Cursor实现增删改查功能使用Cursor增加和修改:
ContentValues values = new ContentValues(); values.put(RadioDbConst.RadioStation.BAND, station.getBand()); values.put(RadioDbConst.RadioStation.FREQUENCY, station.getFrequencyStr()); values.put(RadioDbConst.RadioStation.IS_STERO, station.isStereoInt()); values.put(RadioDbConst.RadioStation.TYPE, station.getType()); ContentResolver resolver = mContext.getContentResolver(); StationInfo mInfo = getCollectStation(station.getBand(), station.getFrequencyStr()); if (null != mInfo) { Log.i(TAG, "collect -- has"); if (mInfo.getType() != 2 || mInfo.isStereoInt() != station.isStereoInt()) { Log.i(TAG, "collect -- update"); String selection = RadioDbConst.RadioStation.TYPE + " = ?" + " and " + RadioDbConst.RadioStation.IS_STERO + " ?"; String[] selectionArgs = { String.valueOf(2), String.valueOf(station.isStereoInt()) }; resolver.update(RadioProvider.CONTENT_URI_COLLECT, values, selection, selectionArgs); } } else { Log.i(TAG, "collect -- insert value:" + values.getAsString(RadioDbConst.SavedStation.FREQUENCY)); resolver.insert(RadioProvider.CONTENT_URI_COLLECT, values); }
使用Cursor删除:
int id = mContext.getContentResolver().delete(RadioProvider.CONTENT_URI_RADIO_STATION, selection, selectionArgs);
使用Cursor查询:
String selection = RadioDbConst.RadioStation.BAND + " = ? " + "and" + RadioDbConst.RadioStation.FREQUENCY + " = ?"; String[] selectionArgs = { fre }; StationInfo si = null; Cursor cursor = mContext.getContentResolver().query(RadioProvider.CONTENT_URI_COLLECT, null, selection, selectionArgs, null); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { int b = cursor.getInt(cursor.getColumnIndex(RadioDbConst.RadioStation.IS_STERO)); int type = cursor.getInt(cursor.getColumnIndex(RadioDbConst.RadioStation.TYPE)); si = new StationInfo(band, fre, b, type); Log.e("si", si.toString()); } cursor.close();
二、DBHelper
1.构造函数private Context mContext; public DatabaseHelper(Context context, String name, CursorFactory factory, int version) { // 必须通过super调用父类当中的构造函数 super(context, name, null, version); mContext = context; try { createDataBase(); } catch (IOException e) { e.printStackTrace(); } } public DatabaseHelper(Context context, String name, int version) { this(context, name, null, version); } public DatabaseHelper(Context context, String name) { this(context, name, StaticCode.DATABASE_VERSION); } public DatabaseHelper(Context context) { this(context, StaticCode.DATABASE_FILEPATH + StaticCode.DATABASE_NAME); }
2.检查数据库是否有效
/** * 检查数据库是否有效 * * @return */ private boolean checkDataBase() { SQLiteDatabase checkDB = null; boolean isCecked = false; String myPath = StaticCode.DATABASE_FILEPATH + StaticCode.DATABASE_NAME; try { checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); if (checkDB != null) { checkDB.close(); isCecked = true; } } catch (Exception e) { } return isCecked; }
3.创建数据库
public void createDataBase() throws IOException { boolean dbExist = checkDataBase(); if (dbExist) { // 数据库已存在,do nothing. } else { // 创建数据库 File dir = new File(StaticCode.DATABASE_FILEPATH); if (!dir.exists()) { dir.mkdirs(); } File dbf = new File(StaticCode.DATABASE_FILEPATH + StaticCode.DATABASE_NAME); if (dbf.exists()) { dbf.delete(); } SQLiteDatabase.openOrCreateDatabase(dbf, null); } }
4.将本地资源文件夹中的数据库复制到刚刚创建的空数据库
/** * Copies your database from your local assets-folder to the just created empty database in the * system folder, from where it can be accessed and handled. * This is done by transfering bytestream. * */ private void copyDataBase() throws IOException{ //Open your local db as the input stream InputStream myInput = myContext.getAssets().open(ASSETS_NAME); // Path to the just created empty db String outFileName = DB_PATH + DB_NAME; //Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); //transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer))>0){ myOutput.write(buffer, 0, length); } //Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } //复制assets下的大数据库文件时用这个 private void copyBigDataBase() throws IOException{ InputStream myInput; String outFileName = DB_PATH + DB_NAME; OutputStream myOutput = new FileOutputStream(outFileName); for (int i = ASSETS_SUFFIX_BEGIN; i < ASSETS_SUFFIX_END+1; i++) { myInput = myContext.getAssets().open(ASSETS_NAME + "." + i); byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer))>0){ myOutput.write(buffer, 0, length); } myOutput.flush(); myInput.close(); } myOutput.close(); }
注意:
execSQL不支持带;的多条SQL语句,只能一条一条的执行,晕了很久才明白,见execSQL的源码注释 (Multiple statements separated by ;s are not supported.)
将把assets下的数据库文件直接复制到DB_PATH,但数据库文件大小限制在1M以下, 如果有超过1M的大文件,则需要先分割为N个小文件,然后使用copyBigDatabase()替换copyDatabase()
5.创建表
db.execSQL("CREATE TABLE IF NOT EXISTS " + RadioDbConst.RadioStation.TABLE_NAME + " (" + RadioDbConst.RadioStation._ID + " integer primary key autoincrement," + RadioDbConst.RadioStation.FREQUENCY + " text," + RadioDbConst.RadioStation.TITLE + " text," + RadioDbConst.RadioStation.BAND + " integer," + RadioDbConst.RadioStation.IS_STERO + " integer," + RadioDbConst.RadioStation.TYPE + " integer);");
6.Android 将数据库文件保存至sdcard中
三、Android SQLite数据库(dictionary.db文件)与apk文件一起发布
四、数据库处理
package cn.arthur.common;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
/**
* @author Joshua
* 用法:
* DBHelper dbHelper = new DBHelper(this);
* dbHelper.createDataBase();
* SQLiteDatabase db = dbHelper.getWritableDatabase();
* Cursor cursor = db.query()
* db.execSQL(sqlString);
* 注意:execSQL不支持带;的多条SQL语句,只能一条一条的执行,晕了很久才明白
* 见execSQL的源码注释 (Multiple statements separated by ;s are not supported.)
* 将把assets下的数据库文件直接复制到DB_PATH,但数据库文件大小限制在1M以下
* 如果有超过1M的大文件,则需要先分割为N个小文件,然后使用copyBigDatabase()替换copyDatabase()
*/
public class DBHelper extends SQLiteOpenHelper {
//用户数据库文件的版本
private static final int DB_VERSION = 1;
//数据库文件目标存放路径为系统默认位置,cn.arthur.examples 是你的包名
private static String DB_PATH = "/data/data/cn.arthur.examples/databases/";
/*
//如果你想把数据库文件存放在SD卡的话
private static String DB_PATH = android.os.Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/arthurcn/drivertest/packfiles/";
*/
private static String DB_NAME = "hello.db";
private static String ASSETS_NAME = "hello.db";
private SQLiteDatabase myDataBase = null;
private final Context myContext;
/**
* 如果数据库文件较大,使用FileSplit分割为小于1M的小文件
* 此例中分割为 hello.db.101 hello.db.102 hello.db.103
*/
//第一个文件名后缀
private static final int ASSETS_SUFFIX_BEGIN = 101;
//最后一个文件名后缀
private static final int ASSETS_SUFFIX_END = 103;
/**
* 在SQLiteOpenHelper的子类当中,必须有该构造函数
* @param context 上下文对象
* @param name 数据库名称
* @param factory 一般都是null
* @param version 当前数据库的版本,值必须是整数并且是递增的状态
*/
public DBHelper(Context context, String name, CursorFactory factory, int version) {
//必须通过super调用父类当中的构造函数
super(context, name, null, version);
this.myContext = context;
}
public DBHelper(Context context, String name, int version){
this(context,name,null,version);
}
public DBHelper(Context context, String name){
this(context,name,DB_VERSION);
}
public DBHelper (Context context) {
this(context, DB_PATH + DB_NAME);
}
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//数据库已存在,do nothing.
}else{
//创建数据库
try {
File dir = new File(DB_PATH);
if(!dir.exists()){
dir.mkdirs();
}
File dbf = new File(DB_PATH + DB_NAME);
if(dbf.exists()){
dbf.delete();
}
SQLiteDatabase.openOrCreateDatabase(dbf, null);
// 复制asseets中的db文件到DB_PATH下
copyDataBase();
} catch (IOException e) {
throw new Error("数据库创建失败");
}
}
}
//检查数据库是否有效
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
String myPath = DB_PATH + DB_NAME;
try{
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/** * Copies your database from your local assets-folder to the just created empty database in the * system folder, from where it can be accessed and handled. * This is done by transfering bytestream. * */ private void copyDataBase() throws IOException{ //Open your local db as the input stream InputStream myInput = myContext.getAssets().open(ASSETS_NAME); // Path to the just created empty db String outFileName = DB_PATH + DB_NAME; //Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); //transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer))>0){ myOutput.write(buffer, 0, length); } //Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } //复制assets下的大数据库文件时用这个 private void copyBigDataBase() throws IOException{ InputStream myInput; String outFileName = DB_PATH + DB_NAME; OutputStream myOutput = new FileOutputStream(outFileName); for (int i = ASSETS_SUFFIX_BEGIN; i < ASSETS_SUFFIX_END+1; i++) { myInput = myContext.getAssets().open(ASSETS_NAME + "." + i); byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer))>0){ myOutput.write(buffer, 0, length); } myOutput.flush(); myInput.close(); } myOutput.close(); }
@Override
public synchronized void close() {
if(myDataBase != null){
myDataBase.close();
}
super.close();
}
/**
* 该函数是在第一次创建的时候执行,
* 实际上是第一次得到SQLiteDatabase对象的时候才会调用这个方法
*/
@Override
public void onCreate(SQLiteDatabase db) {
}
/**
* 数据库表结构有变化时采用
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories