将数据库从资产复制到设备SD卡,删除表中的数据

时间:2014-03-10 13:46:35

标签: android sqlite

我正在使用此代码将资产文件夹中的数据库复制到我的Device Sd卡

private void copyDataBase() throws IOException {
        try {

            InputStream mInputStream = mContext.getAssets().open(DB_NAME);

            String outFileName = DB_PATH + DB_NAME;



            OutputStream mOutputStream = new FileOutputStream(outFileName);

            byte[] buffer = new byte[1024];
            int length;

            while ((length = mInputStream.read(buffer)) > 0) {
                mOutputStream.write(buffer, 0, length);
            }

            mOutputStream.flush();
            mOutputStream.close();
            mInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

它工作正常并将数据库复制到我的设备所需文件夹,但是当我检查表中的数据时,所有数据都消失了,表是空的,我在Stack中搜索以获得满意的想法或回答,但他们都是关于如何复制,任何想法?

4 个答案:

答案 0 :(得分:1)

我现在正在做这件事并且它正在运作。所以我分享我的代码......可能这会对你有帮助。

File file = new File(Environment.getExternalStorageDirectory(), "my.db");

InputStream  in  = null;
OutputStream out = null;
try {
    in  = getAssets().open("my.db"); //.I'm in a service, so I don't need context
    out = new FileOutputStream(file);

    int count = 0; 
    byte[] buffer = new byte[1024*4];
    while ((count = in.read(buffer)) != -1) {
       out.write(buffer, 0, count);
       out.flush();
    }
 } catch (IOException err) {
    Log.e(TAG, err.getMessage(), err);

 } finally {
   if (in != null) 
      try { in.close(); } 
      catch (IOException ignore) {  }
   if (out != null) 
      try { out.close(); } 
      catch (IOException ignore) {  }
 }

编辑1

此处为SQLiteOpenHelper代码

public class SchemaHelper extends SQLiteOpenHelper {

    static final private String DATABASE_NAME = "my.db";
    static final private int DATABASE_VERSION = 1;  

    private SchemaHelper( Context context ) {
       super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate( SQLiteDatabase db ) {
       /* The database has 6 tables pre-populated */
       /* This one is the only created at runtime */
       /* and editable by the user */
       ShoppingListTable.onCreate(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
       /* The database has 6 tables pre-populated */
       /* This one is the only created at runtime */
       /* and editable by the user */
       ShoppingListTable.onUpgrade(db, oldVersion, newVersion);
    }
}

编辑2

ShoppingListTable是一个帮助程序静态类,用于定义列字段和创建/升级。这是在运行时创建的唯一表,所有其他表都是预先创建和预填充的。

public class ShoppingListTable {

   static final public String COLUMN_PRODUCT_ID = BaseColumns._ID;
   static final public String COLUMN_PARSE_OBJECT_ID = "objectId";
   static final public String COLUMN_LAST_UPDATE = "lastUpdate";
   static final public String TABLE_NAME = "ShoppingList";

   static 
   public void onCreate(SQLiteDatabase database) {
      StringBuilder sql = new StringBuilder();
      sql.append("CREATE TABLE ").append(TABLE_NAME).append(" (");
      sql.append(COLUMN_PRODUCT_ID).append(" INTEGER PRIMARY KEY NOT NULL, ");
      sql.append(COLUMN_PARSE_OBJECT_ID).append(" TEXT, ");
      sql.append(COLUMN_LAST_UPDATE).append(" INTEGER DEFAULT -1, ");
      sql.append(COLUMN_SYNCSTATE).append(" INTEGER DEFAULT 0 ");
      sql.append(");");

      database.execSQL(sql.toString());
   }

   static
   public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
      Log.w( ShoppingListTable.class.getName(), "Upgrading database from version "
         + oldVersion + " to " + newVersion + ", which will destroy all old data" );
      database.execSQL("DROP TABLE IF EXISTS " + ShoppingListTable.TABLE_NAME );
      ShoppingListTable.onCreate(database);
   }
}

答案 1 :(得分:0)

试试这个。这项工作对我来说......

String outFileName = "/data/data/" + ctx.getPackageName() + "/databases/YOUR_DB";

预初始化的DB不应具有任何文件扩展名。 希望这可以帮助你

答案 2 :(得分:0)

尝试使用缓冲流,如下所述,使用适当的条件和try..catch。

BufferedInputStream in = new BufferedInputStream(new FileInputStream(fromFileName));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(toFileName));
byte[] buff = new byte[1024];
int len;
try{
while ((len = in.read(buff,0,buff.lenght())) > 0){
  out.write(buff, 0, len);
}
}catch(Exception e){
  e.printStackTrace()
}
out.flush();    
out.close();
in.close();

答案 3 :(得分:-1)

DB文件应该是

static File DB_FILE = context.getDatabasePath("databasename");

如果您的数据库大于1MiB,则必须将其拆分为块

在这里查看我的答案

Getting “Failed to open database” error when copying a sqlite database from assets In Android 4.2

你也可以看看

Load files bigger than 1M from assets folder