sdcard中的android SQLite数据库

时间:2013-01-28 10:56:25

标签: android sqlite

我想知道android sqlite中的一件事。

我在sdcard中创建了我的数据库。所以没有`upgradege()方法。

public class DatabaseClass
{
    public static final String  DATABASE_FILE_PATH = "/sdcard";
    public static final String  DATABASE_NAME = "testDatabase";

    public static final String TRACKS_TABLE_CREATE =
        "create table if not exists casecategory (_id INTEGER primary key autoincrement, "
        + "category_name TEXT not null);";

    public SQLiteDatabase database;

    public DatabaseClass()
    {  
        try
        {
            database = SQLiteDatabase.openOrCreateDatabase(DATABASE_FILE_PATH + File.separator + DATABASE_NAME, null);
            createTables();
        }

        catch (SQLiteException ex)
        {
            Log.e("Hello", "error -- " + ex.getMessage(), ex);
        }
        finally
        {
            database.close();
        }
    }

在内部记忆中我们创建如下: -

public class DatabaseClass extends SQLiteOpenHelper 
{
    /*Constants */
    public final static String DATABASE_NAME ="localdbfile.db";
    public final static String NAME ="name";
    public final static String ADDRESS ="address";


    public final static String CITY ="city";

    public DatabaseClass(Context context) {
        super(context, DATABASE_NAME, null, 1);
        // TODO Auto-generated constructor stub
        }

    @Override
    public void onCreate(SQLiteDatabase db) {
    db.execSQL( "CREATE TABLE mylistdata(_id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT, address TEXT,city TEXT);");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP Table mylistdata");
        onCreate(db);

    }

}

在内部记忆中,我们更改version号码并调用upgrade()。升级数据库。

如果我想在upgrade数据库中sdcard数据库版本。

如果可能,我该怎么做呢。

1 个答案:

答案 0 :(得分:7)

您可以将数据库直接存储在SD卡中,如下所示:

static class DatabaseClass extends SQLiteOpenHelper {

    DatabaseClass(final Context context) {
        super(context, Environment.getExternalStorageDirectory()
                + File.separator + "/DataBase/" + File.separator
                + DATABASE_NAME, null, DATABASE_VERSION);
    }

如果您将数据库存储在内部存储器中,那么您也可以将数据库从内部存储器复制到SD卡:)

以下是如何将数据复制到SD卡的示例:

InputStream myInput = new FileInputStream("/data/data/pack_name/databases/databasename.db");

File directory = new File("/sdcard/some_folder");
if (!directory.exists()) {
    directory.mkdirs();
}

OutputStream myOutput = new FileOutputStream(directory.getPath() + "/AppName.backup");

byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
    myOutput.write(buffer, 0, length);
}

myOutput.flush();
myOutput.close();
myInput.close();