kos*_*sas 2 sqlite performance android android-sqlite android-room
所以我说非常复杂的数据库,它使用many to many数据库设计foreign keys并连接表和它的Room数据库。我想为它创建备份系统,因为它是离线应用程序,我需要导出数据库并将其存储到谷歌驱动器的应用程序文件夹。最近几天我已经阅读了很多关于它但仍然有点困惑我看到有方法可以将数据库导出为CSV,JSON,excel文件或仅作为.db文件,但是这样做的最佳实践是什么以及专业人员如何处理用它?
几乎不需要做任何复杂的事情,只需保存 SQLiteDatabase 文件即可。
基本上关闭 Room db 然后保存文件。
例如,以下是一个非常基本的示例,它保存到名为 DBsaves 的子目录中的下载目录:-
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resetSequenceAction();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
verifyStoragePermissions(this);
}
}
@Override
protected void onStart() {
super.onStart();
mTestDB = Room.databaseBuilder(this,TestDatabase.class,TestDatabase.DBNAME).build();
addSomeData();
addSomeData();
addSomeData();
addSomeData();
mTestDB.close();
File dbfile = this.getDatabasePath(TestDatabase.DBNAME);
File sdir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"DBsaves");
String sfpath = sdir.getPath() + File.separator + "DBsave" + String.valueOf(System.currentTimeMillis());
if (!sdir.exists()) {
sdir.mkdirs();
}
File savefile = new File(sfpath);
try {
savefile.createNewFile();
int buffersize = 8 * 1024;
byte[] buffer = new byte[buffersize];
int bytes_read = buffersize;
OutputStream savedb = new FileOutputStream(sfpath);
InputStream indb = new FileInputStream(dbfile);
while ((bytes_read = indb.read(buffer,0,buffersize)) > 0) {
savedb.write(buffer,0,bytes_read);
}
savedb.flush();
indb.close();
savedb.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void verifyStoragePermissions(Activity activity) {
final int REQUEST_EXTERNAL_STORAGE = 1;
String[] PERMISSIONS_STORAGE = {
//Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
int permission = ActivityCompat.checkSelfPermission(
activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意 onCreate 和 verifyStoragePermissions 方法仅用于获取写入外部存储的权限(注意用户权限也在清单中设置)。
运行后:-
然后将文件复制到 PC 并使用 SQLite 管理器打开:-
这完全符合预期,并且具有高度可移植性,即您可以将其放入任何 SQLite 工具中(此类工具使用的 SQLite 版本可能是一个限制因素)