0
我是Android開發人員的新手。我從資產中使用.db文件。我可以創建新表嗎?我從資產中使用.db文件,我如何創建新表?
我是Android開發人員的新手。我從資產中使用.db文件。我可以創建新表嗎?我從資產中使用.db文件,我如何創建新表?
如果您的數據庫處於Assets中,您必須在應用程序的開始處將其複製到本地路徑中。請參見下面的代碼:
try {
String inputFilename = "database_name.db";
InputStream input = getContext().getAssets().open(inputFilename);
String outputFilename = getContext().getFilesDir().getPath()+inputFilename;
OutputStream output = new FileOutputStream(outputFilename);
byte[] buffer = new byte[1024];
int length;
while((length = input.read(buffer)) > 0) {
output.write(buffer,0,length);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
現在,你可以打開你的DB:
SQLiteDatabase db = SQLiteDatabase.openDatabase(activity.getFilesDir().getPath()+"database_name.db",null,SQLiteDatabase.OPEN_READWRITE);
try {
db.beginTransaction();
db.execSQL("CREATE TABLE IF NOT EXISTS table_name (...)");
db.setTransactionSuccessful();
} catch (SQLException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} finally {
db.endTransaction();
}
使用適用於Firefox的Sqlite Manager插件打開Sqlite數據庫。創建和刪除表可以使用sqlite管理器完成。
顯然,除非你想移動數據庫的外部存儲你不需要特殊的權限。 – Emisilve86