将db从资产复制到设备内存中的db文件夹

时间:2014-07-19 08:24:23

标签: java android database sqlite

我尝试通过将资产文件夹从资产文件夹复制到设备来使用SQLite数据库。如果正在复制db,我还使用DDMS进行了检查。一切都很好但是当我打开复制的数据库时,里面没有表格,即它是一个空白数据库。

请帮我如何复制数据库及其表格。

这是我的DBHelper类: -

public class DBHelper extends SQLiteOpenHelper {  

private static String DB_NAME = "collegeDb2";  
private SQLiteDatabase db;  
private final Context context;  
private String DB_PATH;  

public DBHelper(Context context) {  
 super(context, DB_NAME, null, 1);  
 this.context = context;  
 DB_PATH = context.getApplicationInfo().dataDir + "/databases/";  
}  

public void createDataBase() throws IOException {  

 boolean dbExist = checkDataBase();  
 if (dbExist) {  

 } else {  
  this.getReadableDatabase();  
  try {  
   copyDataBase();  
  } catch (IOException e) {  
   throw new Error("Error copying database");  
  }  
 }  
}  

private boolean checkDataBase() {  
 File dbFile = new File(DB_PATH + DB_NAME);  
 return dbFile.exists();  
}  

private void copyDataBase() throws IOException {  

 InputStream myInput = context.getAssets().open(DB_NAME);  
 String outFileName = DB_PATH + DB_NAME;  
 OutputStream myOutput = new FileOutputStream(outFileName);  
 byte[] buffer = new byte[1024];  
 int length;  
 while ((length = myInput.read(buffer)) > 0) {  
  myOutput.write(buffer, 0, length);  
 }  

  // Close the streams  
 myOutput.flush();  
 myOutput.close();  
 myInput.close();  

}  

public Cursor getColleges() {  
 String myPath = DB_PATH + DB_NAME;  
 db = SQLiteDatabase.openDatabase(myPath, null,  
  SQLiteDatabase.OPEN_READONLY);  
 Cursor c = db.rawQuery("SELECT * FROM collegeslist", null); 
  // Note: colleges is the one table in External db. Here we trying to access the records of table from external db.  
 return c;
}  

 public Cursor getProducts() {  
  String myPath = DB_PATH + DB_NAME;  
  db = SQLiteDatabase.openDatabase(myPath, null,  
    SQLiteDatabase.OPEN_READONLY);  
    Cursor d = db.rawQuery("SELECT * FROM productslist", null);
   // Note: products is the one table in External db. Here we trying to access the records of table from external db.  
  return d;
 }  

@Override  
public void onCreate(SQLiteDatabase db) {  
 // TODO Auto-generated method stub  

}  

@Override  
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
 // TODO Auto-generated method stub 

}  

我可以在onCreate()中使用此代码添加表格: -

public void onCreate(SQLiteDatabase db) {   
        String CREATE_collegeslistTable = "CREATE TABLE collegeslist  ( "
            + "_id INTEGER PRIMARY KEY  NOT NULL ,Organization_Name VARCHAR DEFAULT (null) ,Organization_No VARCHAR DEFAULT (null) ,Assigned_To VARCHAR DEFAULT (null) ,Billing_Address VARCHAR DEFAULT (null) ,Billing_City VARCHAR DEFAULT (null) )";   
         db.execSQL(CREATE_collegeslistTable);
        String CREATE_productslistTable = "CREATE TABLE productslist  ( "
                + "_id INTEGER PRIMARY KEY  NOT NULL ,Product_Name VARCHAR DEFAULT (null) ,Part_Number VARCHAR DEFAULT (null) ,Manufacturer VARCHAR DEFAULT (null) ,Product_Category VARCHAR DEFAULT (null) ,Vendor_Name VARCHAR DEFAULT (null), Unit_Price DOUBLE DEFAULT (null), Usage_Unit VARCHAR DEFAULT (null), Unit INTEGER DEFAULT (null) )";   
             db.execSQL(CREATE_productslistTable);
 }  

但这只会在db中创建两个空白表,我也想要它们内部的数据。由于表中有数百个条目,因此我无法手动添加它们。

请有人帮忙....

2 个答案:

答案 0 :(得分:0)

您需要在数据库名称中附加db文件的路径:

private static String DB_NAME = "collegeDb2";  

应该是:

private static String DB_NAME = "<path_where_you_are_copying_db>/collegeDb2.db";

示例:如果您在此处复制了您的db文件:/storage/sdcard0/test.db,那么它应该是:

private static String DB_NAME = "/storage/sdcard0/test.db"

此外,您不需要createDatabase()方法。如果数据库被调用super时不存在,将自动创建数据库

答案 1 :(得分:0)

所以我最后通过使用以下DBHelper课程来实现它: -

public class DBHelper extends SQLiteOpenHelper {

public SQLiteDatabase database = null;
public File databaseFile;
public static String databaseName = "collegeDb.sqlite";
public String databasePath = "";
Context mContext;

public DBHelper(Context paramContext) {

    super(paramContext, databaseName, null, 1);
    this.mContext = paramContext;

    Log.d("data", "package name:" + paramContext.getPackageName());

    this.databasePath = ("data/data/" + paramContext.getPackageName() + "/databases/"+databaseName);
    this.databaseFile = new File(this.databasePath);
    if (!this.databaseFile.exists())
        try {
            deployDataBase(DBHelper.databaseName, this.databasePath);
            return;
        } catch (IOException localIOException) {
            localIOException.printStackTrace();
        }
}

private void deployDataBase(String dbNAme, String dbPath)
        throws IOException {
    InputStream localInputStream = this.mContext.getAssets().open(dbNAme);
    FileOutputStream localFileOutputStream = new FileOutputStream(dbPath);
    byte[] arrayOfByte = new byte[1024];
    while (true) {
        int i = localInputStream.read(arrayOfByte);
        if (i <= 0) {
            localFileOutputStream.flush();
            localFileOutputStream.close();
            localInputStream.close();
            return;
        }
        localFileOutputStream.write(arrayOfByte, 0, i);
    }
}

@Override
public synchronized void close() {

    if (database != null)
        database.close();

    super.close();

}
@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

}

@Override  
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
 // TODO Auto-generated method stub 

} 
/**
 * Getting all colleges
 * returns list of colleges
 * */
public List<String> getAllColleges(){
    List<String> colleges = new ArrayList<String>();

    // Select All Query
    String selectQuery = "SELECT * FROM collegeslist";

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            colleges.add(cursor.getString(1));
        } while (cursor.moveToNext());
    }

    // closing connection
    cursor.close();
    db.close();

    // returning colleges
    return colleges;
}

 /**
  * Getting all products
  * returns list of products
  * */
 public List<String> getAllProducts(){
     List<String> products = new ArrayList<String>();

     // Select All Query
     String selectQuery = "SELECT * FROM productslist";

     SQLiteDatabase db = this.getReadableDatabase();
     Cursor cursor = db.rawQuery(selectQuery, null);

     // looping through all rows and adding to list
     if (cursor.moveToFirst()) {
         do {
             products.add(cursor.getString(1));
         } while (cursor.moveToNext());
     }

     // closing connection
     cursor.close();
     db.close();

     // returning products
     return products;
 }
}

感谢您的帮助朋友。