1

我正在尝试将我的 sqlite 数据库保存到 SD 卡。我尝试了几件事,但我无法弄清楚,有些给了我错误,例如,虽然它正在创建数据库,但它找不到表SD 卡。我最终删除了所有内容...

我需要添加或更改什么才能保存到他的 SD 卡?为了清楚起见,我不是想把它复制到 SD 卡上,我想把它保存在 SD 卡上而不是内部存储上。

到目前为止,这是我的数据库。

public class Backup_DB extends SQLiteOpenHelper {
private static final String DB_NAME = "backup.db";
private static final int DB_VERSION_NUMBER = 1;
private static final String DB_TABLE_NAME = "backup";
private static final String TAG = "CountriesDbAdapter";
private final Context mCtx;
private Backup_DB mDbHelper;
public static final String KEY_ROWID = "_id";
static final String DB_COLUMN_1_NAME = "country_name";

static final String DB_COLUMN_3_NAME = "country_price";

private static final String DB_CREATE_SCRIPT = "create table "
        + DB_TABLE_NAME
        + " ( _id INTEGER PRIMARY KEY AUTOINCREMENT,country_name text unique,country_price REAL)";

private SQLiteDatabase sqliteDBbackup = null;

public Backup_DB(Context context) {
    super(context, DB_NAME, null, DB_VERSION_NUMBER);
    this.mCtx = context;
}

public Backup_DB open() throws SQLException {
    mDbHelper = new Backup_DB(mCtx);
    sqliteDBbackup = mDbHelper.getWritableDatabase();
    return this;
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO: Implement onUpgrade

}

@Override
public void onCreate(SQLiteDatabase sqliteDBbackup) {
    Log.i("onCreate", "Creating the database...");
    sqliteDBbackup.execSQL(DB_CREATE_SCRIPT);
}

public void openDB() throws SQLException {
    Log.i("openDB", "Checking sqliteDBbackup...");
    if (this.sqliteDBbackup == null) {
        Log.i("openDB", "Creating sqliteDBbackup...");
        this.sqliteDBbackup = this.getWritableDatabase();

    }
}

public void closeDB() {
    if (this.sqliteDBbackup != null) {
        if (this.sqliteDBbackup.isOpen())
            this.sqliteDBbackup.close();
    }
}

public void insertCountry(String countryName, String countryPrice) {

    sqliteDBbackup.execSQL("INSERT OR IGNORE INTO " + DB_TABLE_NAME
            + "(country_name) VALUES('" + countryName + "')");

    sqliteDBbackup.execSQL("UPDATE " + DB_TABLE_NAME
            + " SET country_price=" + countryPrice
            + " WHERE country_name='" + countryName + "';");
}
4

1 回答 1

1

SQLiteOpenHelper isn't built for creating external database. In the SQLiteOpenHelper construtor, context is passed in and it is used to create files in the package folder. Have a look at the source code SQLiteOpenHelper . You can however create in internal first, then exporting it. Remember to add permissions.

Try this helper class I wrote DBAssetHelper

Export:

new AssetDatabaseHelper(this,"test.sqlite").exportDatabase("/flder_toExport/canBerenamedhere.sqlite");
于 2013-07-17T20:37:28.727 回答