android:从资产文件夹(sqllite db)导出数据并将其导入app的数据库

时间:2015-07-21 11:08:17

标签: android eclipse sqlite

更新

我找到了这个链接

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

任何人都可以解释如何使用此

编写更新/插入语句

___________________________________________________________________________

问题

我正在尝试创建一种方法,我可以将存储在sqllite数据库中的数据复制到我的应用程序的数据库中。结构类似。我只是不想逐个插入行。

我正在寻找一种方法,通过该方法将存储在assets文件夹或外部存储器中的预先输入的数据复制到我的应用程序db。

我无法在我的应用中填充数据。我不想为每一行和每列编写5000个插入语句。

任何人都可以建议一种方法。我是android的新手,所以请详细解释或提供链接。

我的数据库帮助程序类

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {
    public  SQLiteDatabase db1;


    // Static Final Variable database meta information

    static final String DATABASE = "assesmenttool.db";
    static final int DATABASE_VERSION = 1;

    //Table Student Details
    static final String TABLEStudent = "StudentDetails";
    static final String S_ID = "_id";
    static final String SchoolID = "SchoolID";
    static final String SchoolName = "schoolname";
    static final String StudentFirstName = "StudentFirstName";
    static final String StudentLastName ="StudentLastName";
    static final String StudentClassLevel ="StudentClassLevel";
    static final String RollNo="RollNo";
    static final String TestDate ="TestDate";

     //Table Response Details   
    static final String TABLEResponse = "TableResponse";
    static final String R_ID = "_id";
    static final String StudentID = "StudentID";
    static final String R_QuestionID = "QuestionID";
    static final String QuestOptionID = "QuestOptionID";

    //Table Question Master
    static final String TableQuestionMaster = "TableQuestionMaster";
    static final String Q_ID= "_id";
    static final String Module_ID = "Module_ID";
    static final String SubModule_ID = "SubModule_ID";
    static final String SubModuleQuestion_ID ="SubModuleQuestion_ID";
    static final String Question_ID= "Question_ID"; 
    static final String Title = "Title";
    static final String Module = "Module";
    static final String TitleDescription = "TitleDescription";
    static final String QuestionText = "QuestionText";
    static final String QuestionImage = "QuestionImage";
    static final String QuestionTemplate = "QuestionTemplate";
    static final String CorrectOptionID = "CorrectOptionID";

    //Table Template Master
    static final String TableTemplateMaster = "TemplateMaster";
    static final String T_ID= "_id";
    static final String Template_ID= "Template_ID"; 
    static final String Name = "Name";
    static final String Description = "Description";

    //Table Question Option 
    static final String TableQuestionOption = "TableQuestionOption";
    static final String TQP_ID= "_id";
    static final String TQP_QuestionID = "QuestionID";
    static final String OptionText = "OptionText";

    //Table Class Master
    static final String TableClassMaster = "TableClassMaster";
    static final String Class_ID= "_id";
    static final String Class = "class";


    // Override constructor
    public DBHelper(Context context) {
        super(context, DATABASE, null, DATABASE_VERSION);

    }


    // Override onCreate method
    @Override
    public void onCreate(SQLiteDatabase db) {


        //Create Table Student Details
        db.execSQL("CREATE TABLE " + TABLEStudent + " ( " + S_ID
                + " INTEGER PRIMARY KEY AUTOINCREMENT, " + SchoolID + " text, "
                + SchoolName + " text, " + StudentFirstName + " text, "  + StudentLastName + " text, " + RollNo + " text," + TestDate + " text," + StudentClassLevel + " text)");


        //Create Table Response Details     
        db.execSQL("CREATE TABLE " + TABLEResponse + " ( " + R_ID
                + " INTEGER PRIMARY KEY AUTOINCREMENT, " + StudentID + " text, "
                + R_QuestionID + " text, " + QuestOptionID + " text)");


        //Create Table Question Master
        db.execSQL("CREATE TABLE " + TableQuestionMaster + " ( " + Q_ID
                + " INTEGER PRIMARY KEY AUTOINCREMENT, " +  Question_ID + " text, " +  Module_ID + " text, " +  SubModule_ID + " text, " +  SubModuleQuestion_ID + " text,  " + Title + " text, "  +  Module + " text," 
                + TitleDescription + " text, " + QuestionText + " text, "  + QuestionImage + " text, " + QuestionTemplate + " text," + CorrectOptionID + " text)");


        //Create Table Template Master
        db.execSQL("CREATE TABLE " + TableTemplateMaster + " ( " + T_ID
                + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Name + " text, "
                + Description + " text)");


        //Create Table Question Option  
        db.execSQL("CREATE TABLE " + TableQuestionOption + " ( " + TQP_ID
                + " INTEGER PRIMARY KEY AUTOINCREMENT, " + TQP_QuestionID + " text, "
                + OptionText + " text)");   

        //Create Table Class Master 
        db.execSQL("CREATE TABLE " + TableClassMaster + " ( " + Class_ID
                + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Class + " text)");   

    }

       public List<String> getAllClasses(){
            List<String> labels = new ArrayList<String>();

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

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

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

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

            // returning lables
            return labels;
        }

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

        // Drop old version table
        db.execSQL("Drop table " + TABLEStudent);
        db.execSQL("Drop table " + TABLEResponse);
        db.execSQL("Drop table " + TableQuestionMaster);
        db.execSQL("Drop table " + TableTemplateMaster);
        db.execSQL("Drop table " + TableQuestionOption);
        db.execSQL("Drop table " + TableClassMaster);
        // Create New Version table
        onCreate(db);
    }




}

我在stackoverflow上找到的SQLLITE副本

我如何将这两者混合在一起。我如何同步这两个sqllite表。 ?

  private static final String DB_NAME = "asset.db";

    private Context context;

    public AssetDatabaseOpenHelper(Context context) {
        this.context = context;
    }

    public SQLiteDatabase openDatabase() {
        File dbFile = context.getDatabasePath(DB_NAME);

        if (!dbFile.exists()) {
            try {
                copyDatabase(dbFile);
            } catch (IOException e) {
                throw new RuntimeException("Error creating source database", e);
            }
        }

        return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
    }

    private void copyDatabase(File dbFile) throws IOException {
        InputStream is = context.getAssets().open(DB_NAME);
        OutputStream os = new FileOutputStream(dbFile);

        byte[] buffer = new byte[1024];
        while (is.read(buffer) > 0) {
            os.write(buffer);
        }

        os.flush();
        os.close();
        is.close();
    }

}

3 个答案:

答案 0 :(得分:1)

这将解决我的答案..

只需使用sqlliteOPenHelper Class ..

的帮助

<强>步骤1

添加copyDataBase()函数..

<强>第二步

像你这样在你的MainActivity中启动它

helper = new DBHelper(this);

        try {

            helper.createDataBase();

    } catch (IOException ioe) {

        throw new Error("Unable to create database");

    }

    try {

        helper.openDataBase();

    }catch(SQLException sqle){

        throw sqle;

    }

您的DBHelper课程类似

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {
    public  SQLiteDatabase db1;


    // Static Final Variable database meta information

    static final String DATABASE = "assesmenttool.db";
    static final int DATABASE_VERSION = 1;

    //Table Student Details
    static final String TABLEStudent = "StudentDetails";
    static final String S_ID = "_id";
    static final String SchoolID = "SchoolID";
    static final String SchoolName = "schoolname";
    static final String StudentFirstName = "StudentFirstName";
    static final String StudentLastName ="StudentLastName";
    static final String StudentClassLevel ="StudentClassLevel";
    static final String RollNo="RollNo";
    static final String TestDate ="TestDate";

     //Table Response Details   
    static final String TABLEResponse = "TableResponse";
    static final String R_ID = "_id";
    static final String StudentID = "StudentID";
    static final String R_QuestionID = "QuestionID";
    static final String QuestOptionID = "QuestOptionID";

    //Table Question Master
    static final String TableQuestionMaster = "TableQuestionMaster";
    static final String Q_ID= "_id";
    static final String Module_ID = "Module_ID";
    static final String SubModule_ID = "SubModule_ID";
    static final String SubModuleQuestion_ID ="SubModuleQuestion_ID";
    static final String Question_ID= "Question_ID"; 
    static final String Title = "Title";
    static final String Module = "Module";
    static final String TitleDescription = "TitleDescription";
    static final String QuestionText = "QuestionText";
    static final String QuestionImage = "QuestionImage";
    static final String QuestionTemplate = "QuestionTemplate";
    static final String CorrectOptionID = "CorrectOptionID";

    //Table Template Master
    static final String TableTemplateMaster = "TemplateMaster";
    static final String T_ID= "_id";
    static final String Template_ID= "Template_ID"; 
    static final String Name = "Name";
    static final String Description = "Description";

    //Table Question Option 
    static final String TableQuestionOption = "TableQuestionOption";
    static final String TQP_ID= "_id";
    static final String TQP_QuestionID = "QuestionID";
    static final String TQP_OptionID = "TQP_OptionID";
    static final String OptionText = "OptionText";

    //Table Class Master
    static final String TableClassMaster = "TableClassMaster";
    static final String Class_ID= "_id";
    static final String Class = "class";




       private static String DB_PATH = "/data/data/com.cldonline.assesmenttool/databases/";

        private static String DB_NAME = "assesmenttool.db";

        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 DBHelper(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();

        }





        // Override onCreate method
        @Override
        public void onCreate(SQLiteDatabase db) {



        }

           public List<String> getAllClasses(){
                List<String> labels = new ArrayList<String>();

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

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

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

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

                // returning lables
                return labels;
            }

           public List<String> getAllOptions(String Qid){
                List<String> options = new ArrayList<String>();

                // Select All Query
                String selectQuery = "SELECT * FROM " + TableQuestionOption +" "+"where QuestionID ='"+Qid+"'";

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

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

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

                // returning lables
                return options;
            }

           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 onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


        }

        public ArrayList<Cursor> getData(String Query){
            //get writable database
            SQLiteDatabase sqlDB = this.getWritableDatabase();
            String[] columns = new String[] { "mesage" };
            //an array list of cursor to save two cursors one has results from the query 
            //other cursor stores error message if any errors are triggered
            ArrayList<Cursor> alc = new ArrayList<Cursor>(2);
            MatrixCursor Cursor2= new MatrixCursor(columns);
            alc.add(null);
            alc.add(null);


            try{
                String maxQuery = Query ;
                //execute the query results will be save in Cursor c
                Cursor c = sqlDB.rawQuery(maxQuery, null);


                //add value to cursor2
                Cursor2.addRow(new Object[] { "Success" });

                alc.set(1,Cursor2);
                if (null != c && c.getCount() > 0) {


                    alc.set(0,c);
                    c.moveToFirst();

                    return alc ;
                }
                return alc;
            } catch(SQLException sqlEx){
                Log.d("printing exception", sqlEx.getMessage());
                //if any exceptions are triggered save the error message to cursor an return the arraylist
                Cursor2.addRow(new Object[] { ""+sqlEx.getMessage() });
                alc.set(1,Cursor2);
                return alc;
            } catch(Exception ex){

                Log.d("printing exception", ex.getMessage());

                //if any exceptions are triggered save the error message to cursor an return the arraylist
                Cursor2.addRow(new Object[] { ""+ex.getMessage() });
                alc.set(1,Cursor2);
                return alc;
            }


        }




}

答案 1 :(得分:0)

我用同样的方法。我有一个帮助类:

public class DatabaseImport {
private static final String TAG = "DataAdapter";

private final DataBaseHelper mDbHelper;

public DatabaseImport(Context context) {
    Context mContext = context;
    mDbHelper = new DataBaseHelper(mContext);
}

public void createDatabase() {
    try {
        mDbHelper.createDataBase();
    } catch (Exception mIOException) {
        Log.e(TAG, mIOException.toString() + "  UnableToCreateDatabase");
        throw new Error("UnableToCreateDatabase");
    }
}
我在DBHelper类中调用的

class DataBaseHelper extends SQLiteOpenHelper {

//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/yourpackagename/databases/";

private static final String DB_NAME = "databasename";

private static final String TAG = "DataBaseHelper"; // Tag just for the LogCat window
//destination path (location) of our database on device
private final Context mContext;
private SQLiteDatabase mDataBase;

public DataBaseHelper(Context context) {
    super(context, DB_NAME, null, 1);// 1? its Database Version
    if (android.os.Build.VERSION.SDK_INT >= 17) {
        DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
    } else {
        DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
    }
    this.mContext = context;
}

public void createDataBase() {
    //If database not exists copy it from the assets

    boolean mDataBaseExist = checkDataBase();
    if (!mDataBaseExist) {
        this.getReadableDatabase();
        this.close();
        try {
            //Copy the database from assests
            copyDataBase();
            Log.e(TAG, "createDatabase database created");
        } catch (IOException mIOException) {
            throw new Error("ErrorCopyingDataBase");
        }
    }
}

//Check that the database exists here: /data/data/your package/databases/Da Name
private boolean checkDataBase() {
    File dbFile = new File(DB_PATH + DB_NAME);
    //Log.v("dbFile", dbFile + "   "+ dbFile.exists());
    return dbFile.exists();
}

//Copy the database from assets
private void copyDataBase() throws IOException {
    InputStream mInput = mContext.getResources().openRawResource(R.raw.kindersporttabelle);
    String outFileName = DB_PATH + DB_NAME;
    OutputStream mOutput = new FileOutputStream(outFileName);
    byte[] mBuffer = new byte[1024];
    int mLength;
    while ((mLength = mInput.read(mBuffer)) > 0) {
        mOutput.write(mBuffer, 0, mLength);
    }
    mOutput.flush();
    mOutput.close();
    mInput.close();
}

@Override
public synchronized void close() {
    if (mDataBase != null)
        mDataBase.close();
    super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {

}

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

}

}

使用普通的DataBaseHandler可以访问和使用数据库:

public class DatabaseHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
//databasename
private static final String DATABASE_NAME = "databasename";
//table names
[...]
//game name column names

[....]

private static Context myContext;

private static DatabaseHandler mInstance = null;

/**
 * Constructor
 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
 */
private DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

public static DatabaseHandler getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new DatabaseHandler(context.getApplicationContext());
    }
    myContext = context;
    return mInstance;
}

@Override
public void onCreate(SQLiteDatabase db) {

    Intent intent = new Intent(myContext, MainActivity.class);
    myContext.startActivity(intent);

    DatabaseImport mDbHelper = new DatabaseImport(myContext);
    try {
        mDbHelper.createDatabase();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + tablename);
    myContext.deleteDatabase(DATABASE_NAME);

    onCreate(db);
}

}

你只需要调整正确的班级名称。这应该工作。祝好运。

答案 2 :(得分:0)

检查this。提供位于项目资产文件夹中的数据库路径。您可以在SQLiteOpenHelper的帮助下复制整个数据库。

public class PlanDetailsSQLiteOpenHelper extends SQLiteOpenHelper {
    private static final String TAG = "SQLiteOpenHelper";

    private final Context context;
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "my_custom_db";

    private boolean createDb = false, upgradeDb = false;

    public PlanDetailsSQLiteOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    /**
     * Copy packaged database from assets folder to the database created in the
     * application package context.
     *
     * @param db
     *            The target database in the application package context.
     */
    private void copyDatabaseFromAssets(SQLiteDatabase db) {
        Log.i(TAG, "copyDatabase");
        InputStream myInput = null;
        OutputStream myOutput = null;
        try {
            // Open db packaged as asset as the input stream
            myInput =context.getAssets().open("your_database_path");

            // Open the db in the application package context:
            myOutput = new FileOutputStream(db.getPath());

            // Transfer db file contents:
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }
            myOutput.flush();

            // Set the version of the copied database to the current
            // version:

            SQLiteDatabase copiedDb = context.openOrCreateDatabase(
                    DATABASE_NAME, 0, null);
            copiedDb.execSQL("PRAGMA user_version = " + DATABASE_VERSION);
           // copiedDb.close();


        } catch (IOException e) {
            e.printStackTrace();
            throw new Error(TAG + " Error copying database");
        } finally {
            // Close the streams
            try {
                if (myOutput != null) {
                    myOutput.close();
                }
                if (myInput != null) {
                    myInput.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new Error(TAG + " Error closing streams");
            }
        }
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.i(TAG, "onCreate db");
        createDb = true;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.i(TAG, "onUpgrade db");
        upgradeDb = true;

    }

    @Override
    public void onOpen(SQLiteDatabase db) {
        Log.i(TAG, "onOpen db");
        if (createDb) {// The db in the application package
            // context is being created.
            // So copy the contents from the db
            // file packaged in the assets
            // folder:
            createDb = false;
            copyDatabaseFromAssets(db);

        }
        if (upgradeDb) {// The db in the application package
            // context is being upgraded from a lower to a higher version.
            upgradeDb = false;
            // Your db upgrade logic here:

        }

    }
}