Android: 从数据库中删除数据

Android: remove data from database

我正在使用 this code (android-sqlite-asset-helper) 从资产文件夹中的文件位置加载数据库。这很好用。

但是refreshing/upgrading数据库的处理并不简单,想知道有没有简单的方法可以在app中手动删除数据库中的所有数据;以便从资产文件加载新数据库。

您可以使用简单的复制文件来覆盖默认数据库中的数据。只需用新的数据库文件覆盖默认数据库即可。 以下代码仅适用于一个文件,因此您需要在此处和那里进行一些更改以使其适用于资产文件。 这里是覆盖数据库文件的方法:

/**
 * Copies the database file at the specified location over the current
 * internal application database.
 **/
 public boolean importDatabase(Context context, String dbPath) throws IOException {

   File OldDbFile = context.getApplicationContext().getDatabasePath(DBSchema.DATABASE_NAME);
   // Close the SQLiteOpenHelper so it will commit the created empty
   // database to internal storage.
   close();
   File newDb = new File(dbPath);
   if (newDb.exists()) {
     FileUtils.copyFile(new FileInputStream(newDb), new FileOutputStream(OldDbFile));
     // Access the copied database so SQLiteHelper will cache it and mark
     // it as created.
     getWritableDatabase().close();

     return true;
  }
  return false;
}

FileUtils class:

public class FileUtils {
  /**
   * Creates the specified <code>toFile</code> as a byte for byte copy of the
   * <code>fromFile</code>. If <code>toFile</code> already exists, then it
   * will be replaced with a copy of <code>fromFile</code>. The name and path
   * of <code>toFile</code> will be that of <code>toFile</code>.<br/>
   * <br/>
   * <i> Note: <code>fromFile</code> and <code>toFile</code> will be closed by
   * this function.</i>
   *
   * @param fromFile - FileInputStream for the file to copy from.
   * @param toFile - FileInputStream for the file to copy to.
   */
  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();
        }
      }
    }
  }
}

我真的忘记了我把copyFile方法放在哪里了:(.

注意一点:当用户清理应用程序数据时,数据库将恢复为默认值。

它似乎在主要 activity 创作中使用这个:

getApplicationContext().deleteDatabase("mydatabase.db");