注:本文代碼參考了網上的例子,忘了什麼地址了,所以無法提供說明,原作者看到勿怪,可以提醒我加上。
有時候自己導入DB文件進行操作,和訪問本地數據庫有點差異。
首先在res下建立一個文件夾raw,然後把DB文件導入進去
然後寫一個方法獲取SQLiteDatabase
private static SQLiteDatabase database;
public static final String DATABASE_FILENAME = "city.db"; // 這個是DB文件名字
public static final String PACKAGE_NAME = "com.diz.db"; // 這個是自己項目包路徑
public static final String DATABASE_PATH = "/data"
+ Environment.getDataDirectory().getAbsolutePath() + "/"
+ PACKAGE_NAME; // 獲取存儲位置地址
public static SQLiteDatabase openDatabase(Context context) {
try {
String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
File dir = new File(DATABASE_PATH);
if (!dir.exists()) {
dir.mkdir();
}
if (!(new File(databaseFilename)).exists()) {
InputStream is = context.getResources().openRawResource(R.raw.city);
FileOutputStream fos = new FileOutputStream(databaseFilename);
byte[] buffer = new byte[8192];
int count = 0;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
database = SQLiteDatabase.openOrCreateDatabase(
databaseFilename, null);
return database;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
用這個方法就可以得到SQLiteDatabase實例對象,然後在activity中
SQLiteDatabase db = openDatabase(this);
然後就可以對數據庫進行操作了。
String sql = "select * from tcity where sBelongCode='11'";
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
while(!c.isAfterLast()) {
String name = c.getString(c.getColumnIndex("sName"));
Log.i("msg", name);
c.moveToNext();
}
這裏只是做一個查詢,然後輸出到logcat中。
SQL語句按照自己需要的寫。