騰訊推出的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