2013-03-28 36 views
1

我有一個應用程序,它創建並更新它自己的MySQL數據庫。我現在想允許用戶導出數據庫副本(用於備份目的),然後在以後再次導入文件。在這個過程中,我不需要改變數據庫的格式。如何將mySQL文件導入到我的Android程序中?

我不確定最好/最簡單的方法來做到這一點。我已經能夠讓我的應用程序使用下面的代碼將數據庫導出到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(); 


    } 
+0

更好地保存在數據庫和SD卡使用數據庫從SD卡.. –

回答

1

我做它是這樣的:

 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(); 
      } 
     } 
    } 
} 

問候

+0

優秀,完美的作品,感謝分享 –

+0

很高興聽到它:) – fenix

相關問題