欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android 数据库导入方法 博客分类: android databasessqliteopenhelper 

程序员文章站 2024-02-09 12:55:28
...

public class MySqliteHelper extends SQLiteOpenHelper {

 

 private static final String dbName = "/data/data/com.Aladin/databases/aladindb.db";
 private static final String DATABASE_PATH = "/data/data/com.Aladin/databases";
 private static final String DATABASE_FILENAME = "aladindb.db";
 private static int VERSION = 1;
 String databaseFileName = DATABASE_PATH + "/" + DATABASE_FILENAME;
 Context myContext;

 public MySqliteHelper(Context context, String name, CursorFactory factory,
   int version) {
  super(context, dbName, factory, VERSION);
  myContext = context;
  checkDBExists();
 }

 // ===================================================================
 // 根据城市名获得City
 @Override
 public void onCreate(SQLiteDatabase db) {
 }

 

 @Override
 public synchronized SQLiteDatabase getReadableDatabase() {
  checkDBExists();
  if (new File(databaseFileName).exists()) {
   SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(
     databaseFileName, null);
   return db;
  } else {
   return null;
  }
 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 }

 // ===================================================================
 private void checkDBExists() {
  // 从资源文件中将数据库创建/data/data/com.Aladin/databases/aladindb.db
  // 1,获得路径
  File dir = new File(DATABASE_PATH);
  if (!dir.exists()) {
   dir.mkdir();
  }
  // 2,获得资源文件
  if (!(new File(databaseFileName).exists())) {
   try {
    // 3,读取资源并创建流
    InputStream is = myContext.getResources().openRawResource(
      R.raw.aladindb);
    FileOutputStream fos = new FileOutputStream(databaseFileName);
    // 4,复制
    byte[] buffer = new byte[8192];
    int count = 0;
    while ((count = is.read(buffer)) > 0) {
     fos.write(buffer, 0, count);
    }
    // 5,关闭流
    fos.close();
    is.close();
   } catch (NotFoundException e) {
    e.printStackTrace();
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }