繁体   English   中英

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

[英]Copy db from assets to db folder in device memory

我试图通过将SQLite数据库从资产文件夹复制到设备来使用它。 我还使用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中仅创建两个空白表,我也希望在其中包含数据。 由于表中有数百个条目,因此我无法手动添加它们。

请有人帮助...。

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

private static String DB_NAME = "collegeDb2";  

应该是这样的:

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

示例:如果您已将数据库文件复制到/storage/sdcard0/test.db ,则该文件应为:

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

另外,您不需要createDatabase()方法。 由于数据库将在super调用时不存在时自动创建

所以最后我通过使用以下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;
 }
}

感谢您的帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM