如何在Android中将数据写入外部数据库

时间:2014-01-11 13:06:50

标签: java android sqlite

我正在使用一个数据库,我从SD卡外部获取它。此外,我有一个数据源作为我编写的用于管理数据库事务的接口。以下是我从sdcard获取db的方法:

File dbFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/Database/MyDB.db");
SQLiteDatabase database = SQLiteDatabase.openSQLiteDatabase.openOrCreateDatabase(dbFile, null);
dataSource = new DataSource(getApplicationContext(), database);

importData(this); // Insert initial data in all tables in database

这是DataSource类:

public class DataSource {

    private SQLiteDatabase db;

    public WordsDS(Context context, SQLiteDatabase database) {
        db = database;
    }

    public void open() throws SQLException {}

    public void close() { db.close(); }

    // Transaction Methods...
}

当我尝试将数据插入数据库中的某个表时,它会崩溃并导致LogCat输出:

Error inserting ...
E/Database(19416): android.database.sqlite.SQLiteException: no such table: ...

我不知道如何将下面的db类与我上面创建的数据库联系起来。需要帮忙。

public class DB extends SQLiteOpenHelper {

    static final String DATABASE_NAME = "MyDB";

    static final String TermTable = "Terms";
    static final String ID = "id";
    static final String Term = "term";
    static final String Type = "type";

    public static final int DATABASE_VERSION = 1;

    private static final String TERM_TABLE_CREATE = "Create table " + TermTable +
        "(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
        Term + " VARCHAR(20) ," +
        Type + " VARCHAR(10))";

    public WordsDB(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
    db.execSQL(TERM_TABLE_CREATE);
        db.execSQL(DEF_TABLE_CREATE);
        db.execSQL(HISTORY_TABLE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        db.execSQL("DROP TABLE IF EXISTS " + TermTable);
        onCreate(db);
    }

}

1 个答案:

答案 0 :(得分:0)

我只需要改变代码的两个方面:

DB 类中:

// Give the path which I want to store my db in
public WordsDB(Context context, String path) {
    super(context, path + File.separator + DATABASE_NAME, null, DATABASE_VERSION);
}

并在DataSource类中:

public class DataSource {

    private DB dbHelper;
    private SQLiteDatabase db;

    public DataSource(Context context, String path) {
        dbHelper = new DB(context, path);
    }

    public void open() throws SQLException {
        db = dbHelper.getWritableDatabase();
    }

    public void close() { db.close(); }

    // Transaction Methods...
}

谢谢Moyeen。