我如何在我的项目中使用预先创建的数据库

时间:2012-02-10 15:28:13

标签: android

package com.m;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class HellowWebView extends SQLiteOpenHelper {
    static final String UR_DB_NAME="mimo.sqlite";
    public static final String KEY_ROWID = "_syid"; 
    public static final String KEY_ROWIDc = "_conid";
    static final String tableName = "CATEGORY";
    static final String New_tableName = "CATEGORY_NEW";
    static final String col_name = "NAME";
    static final String col_id = "PARENT_ID";
    static final String col_name_new = "NAME";
    static final String col_id_new = "PARENT_ID";
    public static final int version='1';
    public static Context context;

    SQLiteDatabase sql;

    public HellowWebView(Context context) {
        super(context, UR_DB_NAME, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        try{
        sql = context.openOrCreateDatabase(UR_DB_NAME, 0, null);
        getWritableDatabase();
        db.execSQL("CREATE TABLE " + New_tableName + "(_syid INTEGER PRIMARY 
KEY,col_name_new TEXT,col_id_new NUMBER)");     
        db.execSQL("INSERT INTO UR_DB_NAME.New_tableName(col_name_new,col_id_new) 
SELECT * from tableName",null);
        db.close();
        }catch(Exception e){
        }
    }

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

2 个答案:

答案 0 :(得分:0)

您可以在创建的db文件中复制现有的db文件:为此,您可以按照以下步骤进行操作 -

  1. 检查现有数据库。 (第一次没有数据库)。
  2. 创建数据库。
  3. 现在,您将在创建的db文件上以实用方式替换预先创建的数据库。
  4. 以下是可供参考的代码:

     private boolean checkDataBase() {
        try {
            String myPath = DB_PATH + DB_NAME;
            try {
                Log.v("---DatabaseHelper--",
                        "---within checkDataBase opening database----");
                myDataBase = SQLiteDatabase.openDatabase(myPath, null,
                        SQLiteDatabase.OPEN_READONLY);
    
            } catch (SQLiteException e) {
                Log.v("---DatabaseHelper--", "---within checkDataBase----" + e);
    
            }
    
            if (myDataBase != null) {
    
                myDataBase.close();
    
            }
        } catch (Throwable e) {
            StringWriter errorLog = new StringWriter();
            e.printStackTrace(new PrintWriter(errorLog));
            serverComm.sendErrorLog(errorLog.toString());
    
        }
    
        return myDataBase != null ? true : false;
    }
    

    然后getReadableDatabase(),为你的应用程序创建一个空白数据库..然后用你的数据库替换它你将它放在资产文件夹中 -

    private void copyDataBase() throws IOException {
        try {
            Log.v("---DatabaseHelper--", "---within copyDataBase----");
    
            // Open your local db as the input stream
            InputStream myInput = myContext.getAssets().open(
                    "DB_NAME.sqlite");
            // Path to the just created empty db
            String outFileName = DB_PATH + DB_NAME;
            // Open the empty db as the output stream
            OutputStream myOutput = new FileOutputStream(outFileName);
            // transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
    
            }
            Log.v("---DatabaseHelper--", "--- after coping----");
            // Close the streams
            myOutput.flush();
            myOutput.close();
            myInput.close();
        } catch (Throwable e) {
            StringWriter errorLog = new StringWriter();
            e.printStackTrace(new PrintWriter(errorLog));
            serverComm.sendErrorLog(errorLog.toString());
    
        }
    
    }
    

答案 1 :(得分:0)

这个here有一个很好的解决方案。

  1. 准备SQLite数据库文件。
  2. 假设您已经创建了sqlite数据库,我们需要对其进行一些修改。 如果您没有sqlite管理器,我建议您下载适用于Win / Linux / Mac的开源SQLite数据库浏览器。

    打开数据库并添加一个名为“android_metadata”的新表,您可以执行以下SQL语句来执行此操作:

    CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')
    

    现在在“android_metadata”表中插入一行文本“en_US”:

    INSERT INTO "android_metadata" VALUES ('en_US')
    

    然后,有必要将表的主id字段重命名为“_id”,以便Android知道绑定表的id字段的位置。 您可以使用SQLite数据库浏览器轻松执行此操作,方法是按编辑表按钮编辑表,然后选择要编辑的表,最后选择要重命名的字段。

    将所有数据表的id字段重命名为“_id”并添加“android_metadata”表后,您的数据库就可以在Android应用程序中使用了。

    enter image description here

    注意:在此图片中,我们会看到表格“类别”和“内容”,其中ID字段已重命名为“_id”,而刚刚添加的表格为“android_metadata”。

    1. 在Android中复制,打开和访问您的数据库 应用
    2. 现在只需将数据库文件放在项目的“assets”文件夹中,并通过从“android.database.sqlite”包中扩展SQLiteOpenHelper类来创建Database Helper类。

      使您的DataBaseHelper类看起来像这样:

      public class DataBaseHelper extends SQLiteOpenHelper{
      
      //The Android's default system path of your application database.
      private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";
      
      private static String DB_NAME = "myDBName";
      
      private SQLiteDatabase myDataBase;
      
      private final Context myContext;
      
      /**
        * Constructor
        * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
        * @param context
        */
      public DataBaseHelper(Context context) {
      
      super(context, DB_NAME, null, 1);
      this.myContext = context;
      }   
      
      /**
        * Creates a empty database on the system and rewrites it with your own database.
        * */
      public void createDataBase() throws IOException{
      
      boolean dbExist = checkDataBase();
      
      if(dbExist){
      //do nothing - database already exist
      }else{
      
      //By calling this method and empty database will be created into the default system path
      //of your application so we are gonna be able to overwrite that database with our database.
      this.getReadableDatabase();
      
      try {
      
      copyDataBase();
      
      } catch (IOException e) {
      
      throw new Error("Error copying database");
      
      }
      }
      
      }
      
      /**
        * Check if the database already exist to avoid re-copying the file each time you open the application.
        * @return true if it exists, false if it doesn't
        */
      private boolean checkDataBase(){
      
      SQLiteDatabase checkDB = null;
      
      try{
      String myPath = DB_PATH + DB_NAME;
      checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
      
      }catch(SQLiteException e){
      
      //database does't exist yet.
      
      }
      
      if(checkDB != null){
      
      checkDB.close();
      
      }
      
      return checkDB != null ? true : false;
      }
      
      /**
        * Copies your database from your local assets-folder to the just created empty database in the
        * system folder, from where it can be accessed and handled.
        * This is done by transfering bytestream.
        * */
      private void copyDataBase() throws IOException{
      
      //Open your local db as the input stream
      InputStream myInput = myContext.getAssets().open(DB_NAME);
      
      // Path to the just created empty db
      String outFileName = DB_PATH + DB_NAME;
      
      //Open the empty db as the output stream
      OutputStream myOutput = new FileOutputStream(outFileName);
      
      //transfer bytes from the inputfile to the outputfile
      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 void openDataBase() throws SQLException{
      
      //Open the database
      String myPath = DB_PATH + DB_NAME;
      myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
      
      }
      
      @Override
      public synchronized void close() {
      
      if(myDataBase != null)
      myDataBase.close();
      
      super.close();
      
      }
      
      @Override
      public void onCreate(SQLiteDatabase db) {
      
      }
      
      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      
      }
      
      // Add your public helper methods to access and get content from the database.
      // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
      // to you to create adapters for your views.
      
      }
      

      就是这样。 现在,您可以创建此DataBaseHelper类的新实例,并调用createDataBase()和openDataBase()方法。请记住将“YOUR_PACKAGE”更改为DB_PATH字符串中的应用程序包命名空间(即:com.examplename.myapp)。

       ...
      
          DataBaseHelper myDbHelper = new DataBaseHelper();
          myDbHelper = new DataBaseHelper(this);
      
          try {
      
          myDbHelper.createDataBase();
      
          } catch (IOException ioe) {
      
          throw new Error("Unable to create database");
      
          }
      
          try {
      
          myDbHelper.openDataBase();
      
          }catch(SQLException sqle){
      
          throw sqle;
      
          }
      
          ...