android中提供了一个轻量的关系型数据库sqlite,至于android底层是怎样实现这个数据的相关操作的呢?很类似java jdbc启动!如果有兴趣的朋友可以查阅相关的源码!SQLiteDatabase.java
public void execSQL(String sql, Object[] bindArgs) throws SQLException {
BlockGuard.getThreadPolicy().onWriteToDisk();
if (bindArgs == null) {
throw new IllegalArgumentException("Empty bindArgs");
}
long timeStart = SystemClock.uptimeMillis();
lock();
if (!isOpen()) {
throw new IllegalStateException("database not open");
}
SQLiteStatement statement = null;
try {
statement = compileStatement(sql);
if (bindArgs != null) {
int numArgs = bindArgs.length;
for (int i = 0; i < numArgs; i++) {
DatabaseUtils.bindObjectToProgram(statement, i + 1, bindArgs[i]);
}
}
statement.execute();
} catch (SQLiteDatabaseCorruptException e) {
onCorruption();
throw e;
} finally {
if (statement != null) {
statement.close();
}
unlock();
}
logTimeStat(sql, timeStart);
}
本人菜鸟,所以就不多说了!我想做过jdbc的朋友一定会觉得很熟悉的!至于最底层的操作嘛,当然是c啦,然后jni!有些大师说,android内部的sqlite操作方式是jdbc,只是有人针对jdbc接口重写了sqlite的实现!
然后说一说SQLiteOpenHelper.java吧
public synchronized SQLiteDatabase getReadableDatabase() {
if (mDatabase != null && mDatabase.isOpen()) {
return mDatabase; // The database is already open for business
}
if (mIsInitializing) {
throw new IllegalStateException("getReadableDatabase called recursively");
}
try {
return getWritableDatabase();
} catch (SQLiteException e) {
if (mName == null) throw e; // Can't open a temp database read-only!
Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e);
}
SQLiteDatabase db = null;
try {
mIsInitializing = true;
String path = mContext.getDatabasePath(mName).getPath();
db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY);
if (db.getVersion() != mNewVersion) {
throw new SQLiteException("Can't upgrade read-only database from version " +
db.getVersion() + " to " + mNewVersion + ": " + path);
}
onOpen(db);
Log.w(TAG, "Opened " + mName + " in read-only mode");
mDatabase = db;
return mDatabase;
} finally {
mIsInitializing = false;
if (db != null && db != mDatabase) db.close();
}
}
事实上getReadableDatabase()方法会先调用getWritableDatabase()方法的!在资源没有限制时,我认为两者的作用是一样的!