首先写一个helper继承SQLiteOpenHelper
private SQLiteDatabase db_r = null; // readable database private SQLiteDatabase db_w = null; // writable database private static DbHelper dbHelper; private DbHelper(Context context) { super(context, DataBaseClass.DB_FILE, null, DataBaseClass.DB_VERSION); } public static synchronized DbHelper getInstance(Context context) { if (dbHelper == null) { dbHelper = new DbHelper(context); } return dbHelper; } @Override public void onCreate(SQLiteDatabase db) { Collection<DbBaseTable> tables = DataBaseClass.sRCMDbTables.values(); Iterator<DbBaseTable> iterator = tables.iterator(); System.out.println("====DBHelp oncreate"); try { db.beginTransaction(); while (iterator.hasNext()) { iterator.next().onCreate(db); } db.setTransactionSuccessful(); } catch (Throwable e) { throw new RuntimeException("DB creation failed: " + e.getMessage()); } finally { db.endTransaction(); } } @Override public synchronized SQLiteDatabase getReadableDatabase() { if (db_r == null || !db_r.isOpen()) { try { db_r = super.getReadableDatabase(); } catch (SQLiteException e) { //TODO Implement proper error handling db_r = null; throw e; } } return db_r; } @Override public synchronized SQLiteDatabase getWritableDatabase() { if (db_w == null || !db_w.isOpen() || db_w.isReadOnly()) { try { db_w = super.getWritableDatabase(); } catch (SQLiteException e) { //TODO Implement proper error handling db_w = null; throw e; } } return db_w; }
创建表封装一个类:
public final class DataBaseClass { private DataBaseClass() {}; public static final int DB_VERSION = 2; static final String DB_FILE = "my.db"; public interface RCMColumns { public static final String account_ID = "account_id"; //INTEGER (long) } public static final class MyTest1Table extends DbBaseTable implements BaseColumns, RCMColumns { private MyTest1Table() { } private static final MyTest1Table sInstance = new MyTest1Table(); static MyTest1Table getInstance() { return sInstance; } private static final String TABLE_NAME = "Mytest1"; /* Columns */ public static final String TEST1 = "test1"; public static final String TEST2 = "test2"; public static final String TEST3 = "test3"; private static final String CREATE_TABLE_STMT = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + account_ID + " INTEGER, " + TEST1 + " TEXT, " // + TEST2 + " TEXT, " + TEST3 + " TEXT" + ");"; @Override String getName() { return TABLE_NAME; } @Override void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_STMT); } } public static final class MyTest2Table extends DbBaseTable implements BaseColumns, RCMColumns { private MyTest2Table() { } private static final MyTest2Table sInstance = new MyTest2Table(); static MyTest2Table getInstance() { return sInstance; } private static final String TABLE_NAME = "Mytest2"; /* Columns */ public static final String TEST4 = "test4"; public static final String TEST5 = "test5"; public static final String TEST6 = "test6"; private static final String CREATE_TABLE_STMT = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + account_ID + " INTEGER, " + TEST4 + " TEXT, " + TEST5 + " TEXT, " + TEST6 + " TEXT" + ");"; @Override String getName() { return TABLE_NAME; } @Override void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_STMT); } } static LinkedHashMap<String, DbBaseTable> sRCMDbTables = new LinkedHashMap<String, DbBaseTable>(); static { sRCMDbTables.put(MyTest1Table.getInstance().getName(), MyTest1Table.getInstance()); // sRCMDbTables.put(MyTest2Table.getInstance().getName(), MyTest2Table.getInstance()); } }
用一个contentProvider来对数据库进行查询,插入操作:
public class MyProvider extends ContentProvider { static final boolean DEBUG_ENBL = false; static final String TAG = "[RC]MyProvider"; /* URI authority string */ public static final String AUTHORITY = "com.pic.optimize.provider.myprovider"; /* URI paths names */ public static final String MyTest1Table = "MyTest1Table"; public static final String MyTest2Table = "MyTest2Table"; private DbHelper dbHelper; @Override public boolean onCreate() { dbHelper = DbHelper.getInstance(getContext()); return true; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { return 0; } @Override public String getType(Uri uri) { return null; } @Override public Uri insert(Uri uri, ContentValues values) { int match = sUriMatcher.match(uri); SQLiteDatabase db; long rowId; try { db = dbHelper.getWritableDatabase(); } catch (SQLiteException e) { throw e; } synchronized (dbHelper) { try { rowId = db.insert(tableName(match), null, values); } catch (SQLException e) { throw e; } } uri = ContentUris.withAppendedId(UriHelper.removeQuery(uri), rowId); getContext().getContentResolver().notifyChange(uri, null); return uri; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { int match = sUriMatcher.match(uri); SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(tableName(match)); SQLiteDatabase db; try { db = dbHelper.getReadableDatabase(); } catch (SQLiteException e) { // TODO Implement proper error handling throw e; } Cursor cursor; synchronized (dbHelper) { try { cursor = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder); } catch (Throwable e) { throw new RuntimeException("Exception at db query: " + e.getMessage()); } } return cursor; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { return 0; } private String tableName(int uri_match) { switch (uri_match) { case MyTest1Table_MATCH: return DataBaseClass.MyTest1Table.getInstance().getName(); case MyTest2Table_MATCH: return DataBaseClass.MyTest2Table.getInstance().getName(); } return null; } /* UriMatcher codes */ private static final int MyTest1Table_MATCH = 10; private static final int MyTest2Table_MATCH = 11; private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { sUriMatcher.addURI(AUTHORITY, MyTest1Table, MyTest1Table_MATCH); sUriMatcher.addURI(AUTHORITY, MyTest2Table, MyTest2Table_MATCH); } }
Activity调用:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); copyDatabase(); DbHelper.getInstance(this); addDataToDataBase(); queryDataBase1(); } private void copyDatabase() { File file = new File("/data/data/com.pic.optimize/databases"); String[] array = file.list(); for(int i=0;i<array.length;i++) { Log.d("TAG","=====array[i]="+array[i]); } File f = new File("/data/data/com.pic.optimize/databases/my.db"); String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath(); File o = new File(sdcardPath+"/my.db"); if(f.exists()) { FileChannel outF; Log.d("TAG","=====file exsit"); try { outF = new FileOutputStream(o).getChannel(); new FileInputStream(f).getChannel().transferTo(0, f.length(),outF); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Toast.makeText(this, "完成", Toast.LENGTH_SHORT).show(); } } private void addDataToDataBase() { try { ContentResolver resolver = this.getContentResolver(); ContentValues values = new ContentValues(); values.put(DataBaseClass.MyTest1Table.TEST1, "cc"); values.put(DataBaseClass.MyTest1Table.account_ID, 1002); resolver.insert(UriHelper.getUri(MyProvider.MyTest1Table), values); } catch (Throwable error) { } } private void queryDataBase1() { ContentResolver resolver = this.getContentResolver(); Cursor cursor = resolver.query(UriHelper.getUri(MyProvider.MyTest1Table), null, null, null, null); cursor.moveToPosition(-1); while(cursor.moveToNext()) { int account = cursor.getInt(1); String test1 = cursor.getString(2); } cursor.close(); }
打印结果是:
12-10 10:28:49.580 11294-11294/com.pic.optimize D/TAG: =====array[i]=my.db
12-10 10:28:49.580 11294-11294/com.pic.optimize D/TAG: =====array[i]=my.db-journal
12-10 10:28:49.581 11294-11294/com.pic.optimize D/TAG: =====file exsit
12-10 10:28:49.610 11294-11294/com.pic.optimize I/System.out: ====account=1002test1=cc