gpt4 book ai didi

android - 如何将 mySQL 文件导入我的 Android 程序?

转载 作者:行者123 更新时间:2023-11-29 00:32:57 26 4
gpt4 key购买 nike

我有一个应用程序可以创建和更新它自己的 MySQL 数据库。我现在想允许用户导出数据库的副本(用于备份目的),然后在以后再次导入文件。在此过程中,我不需要更改数据库的格式。

我不确定执行此操作的最佳/最简单方法。我已经能够使用下面的代码让我的应用程序将数据库导出到 SD 卡,但问题是 - 如何让我的应用程序再次导入该文件?

    try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();

Toast.makeText(getBaseContext(), sd.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(getBaseContext(), data.toString(), Toast.LENGTH_LONG).show();

if (sd.canWrite()) {
String currentDBPath = "//data//"+ packageName +"//databases//"+ class_dbname; //dbList[0];
String backupDBPath = "//data//"+ class_dbname; //dbList[0];
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);

FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(), Toast.LENGTH_LONG).show();

}
} catch (Exception e) {

Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();


}

最佳答案

我是这样做的:

     public boolean importDatabase(String dbPath) throws IOException {
// Close the SQLiteOpenHelper so it will commit the created empty
// database to internal storage.
close();
File newDb = new File(dbPath);
File oldDb = new File(DB_FILEPATH);
if (newDb.exists()) {
FileUtils.copyFile(new FileInputStream(newDb), new FileOutputStream(oldDb));
// Access the copied database so SQLiteHelper will cache it and mark
// it as created.
DBHelper.getWritableDatabase().close();
return true;
}
return false;
}

“copyFile()”方法是:

public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
FileChannel fromChannel = null;
FileChannel toChannel = null;
try {
fromChannel = fromFile.getChannel();
toChannel = toFile.getChannel();
fromChannel.transferTo(0, fromChannel.size(), toChannel);
} finally {
try {
if (fromChannel != null) {
fromChannel.close();
}
} finally {
if (toChannel != null) {
toChannel.close();
}
}
}
}

问候

关于android - 如何将 mySQL 文件导入我的 Android 程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15687464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com