腾讯推出的WCDB开源数据库架构对我们开发者来说更加简单了。它的基本功能和优点小伙伴们可以去官网上去看一下,这里我就不多说了,下面我就直接入主题了。
1,添加WCDB的依赖
dependencies { compile 'com.tencent.wcdb:wcdb-android:1.0.0'} 也可以直接导入jar和so到我们的项目中来,这个等下在我的项目
地址上面会有。
2,我们新建一个数据库管理类DataBaseManger,首先初始化数据库,
public class DatabaseManager { @SuppressLint("StaticFieldLeak") private static DatabaseManager instance = new DatabaseManager(); private volatile SQLiteDatabase database; private static final int CURRENT_VERSION = 1; //数据库版本号 private volatile boolean inited = false; @SuppressLint("StaticFieldLeak") private static Context mContext; private DatabaseManager() { } public static void init(Context context) { mContext = context.getApplicationContext(); } public static DatabaseManager getInstance() { return instance; } /** * 初始化数据库 */ public synchronized void initDatabase(int id) { if (inited) //这里默认为false 保证数据库只初始化一次 { return; } String dbName = String.valueOf(id); createDirsInCache(dbName); dbName += ".db"; if (BuildConfig.DEBUG) { File file = null; if (!exist(id, dbName)) { file = createUserDbForDebug(id, dbName);//创建db } else { file = getUserDbForDebug(id, dbName); } if (file == null) { throw new RuntimeException("db file is not found"); } database = SQLiteDatabase.openOrCreateDatabase(file, null); openForeignKeySupport(); } else { database = SQLiteDatabase.openOrCreateDatabase( mContext.getDatabasePath(dbName), null); openForeignKeySupport(); } if (BuildConfig.DEBUG) { database.setTraceCallback(new SQLiteTrace() { @Override public void onSQLExecuted(SQLiteDatabase sqLiteDatabase, String s, int i, long l) { } @Override public void onConnectionPoolBusy(SQLiteDatabase db, String sql, List<String> requests, String message) { for (String req : requests) { } db.dump(new Printer() { @Override public void println(String x) { } }, true); } @Override public void onDatabaseCorrupted(SQLiteDatabase sqLiteDatabase) { } }); } try { database.beginTransaction(); //开启事务 if (0 != database.getVersion() && CURRENT_VERSION > database.getVersion()) { // 升级表 } else {
//创建表 } database.setVersion(CURRENT_VERSION); database.setTransactionSuccessful(); } finally { database.endTransaction(); } inited = true; } /** * 在app缓存目录中创建自定义目录 */ public static void createDirsInCache(String dirPath) { createDirs(getExternalFilesPath() + File.separator + dirPath); } /** * 获取到app缓存目录 getPath()会忽略最后的“/” */ public static String getExternalFilesPath() { return getExternalFilesDir().getPath(); } /** * 获取到app缓存目录 */ public static File getExternalFilesDir() { return mContext.getExternalFilesDir(null); } /** * 创建多级目录 */ public static boolean createDirs(String path) { if (TextUtils.isEmpty(path)) { return false; } try { File f = new File(path); if (!f.exists()) { return f.mkdirs(); } } catch (Exception e) { e.printStackTrace(); } return false; } /** * 开启Sqlite的外键支持 */ private void openForeignKeySupport() { if (!database.isReadOnly()) { database.execSQL("PRAGMA foreign_keys=ON;"); } } private boolean exist(int id, String filename) { File file = getUserDbForDebug(id, filename); return null != file && file.exists() && file.length() > 0; } private static File getUserDbForDebug(int id, String name) { if (TextUtils.isEmpty(name)) { return null; } return new File(mContext.getExternalFilesDir(null), id + File.separator + name); } private static File createUserDbForDebug(int id, String name) { if (TextUtils.isEmpty(name)) { return null; } File file = new File(mContext.getExternalFilesDir(null), id + File.separator + name); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { file = null; } } return file; } /** * 释放数据库 */ public synchronized void releaseDatabase() { if (null != database) { database.close(); database = null; inited = false; } }
需要注意的是导包的时候注意一下是tencent包下面的SQLiteDatabase
3,数据库创建好了,下面我们来创建表
推荐大家使用
public interface IBaseTable { /** * * 创建数据库表 * * @param db */ void createTable(SQLiteDatabase db); /** * 更新数据库表 * * @param db */ void updateTable(SQLiteDatabase db); }
然后需要建什么表就实现这个接口,规范子类必须实现这2个方法,以免漏掉
子类实现方法, 创建表 %s与下面的常量一一对应
@Override public void createTable(SQLiteDatabase db) { String sql = String.format(Locale.getDefault(), "CREATE TABLE IF NOT EXISTS %s (%s INTEGER ,%s TEXT)", TABLE_NAME, ID, SCHOOL_NAME); db.execSQL(sql); } @Override public void updateTable(SQLiteDatabase db) { createTable(db); }
到这里数据库创建表创建就完成了
项目地址https://download.csdn.net/download/lmy545x/10500316