如何向assets文件夹中的数据库文件插入数据?[英] How to insert data into the database file which is in the assets folder

本文是小编为大家收集整理的关于如何向assets文件夹中的数据库文件插入数据?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我创建了一个SQLite文件,并将其放在资产文件夹中.现在,我能够从该文件中读取数据,但是我不知道如何写入此数据库文件.我需要以用户名为单位,并将其存储在该数据库文件中.我在网络和SO上搜索了,但是有一些普通数据库插入的示例.

任何人都可以告诉我如何将值存储到数据库文件中.我需要存储用户名并得分.只是将其视为字符串,请给我一个例子.

推荐答案

您不应该在资产文件夹中创建数据库,因为我们只能从资产文件夹中读取数据.

实际上,您应该在默认的内部文件夹中创建数据库,即 data/data/[package-name]/databases ,也可以在sdcard中创建数据库,并且可以执行读取write操作但是,如果没有SDCARD,它当然不会运行.

以下是在sdcard中创建数据的代码: -

    private SQLiteDatabase db;
    private static Context cntxt;

    public static File filename = null;
    public static String DATABASE_FILE_PATH_EXTERNAL = null;

    public DBHelper(Context context) {
            super(context, DATABASE_NAME, null,1);
            cntxt = context;
            try{
                try{
                    filename = Environment.getExternalStorageDirectory();
                }catch(Exception e){
                    Toast.makeText(DbHelper.cntxt, "Please Insert SD card To create Database", Toast.LENGTH_LONG).show();
                    Log.e("Log",e.getMessage(),e.fillInStackTrace());
                }

                DATABASE_FILE_PATH_EXTERNAL = filename.getAbsolutePath()+File.separator+DATABASE_NAME;

                //  db = SQLiteDatabase.openDatabase(DATABASE_FILE_PATH_EXTERNAL, null, SQLiteDatabase.OPEN_READWRITE + SQLiteDatabase.CREATE_IF_NECESSARY);
            }catch(Exception e){

                Log.e("Log",e.getMessage(),e.fillInStackTrace());
            }
        }



        @Override
        public synchronized SQLiteDatabase getWritableDatabase() {
            // TODO Auto-generated method stub
            try{
                db = SQLiteDatabase.openDatabase(DATABASE_FILE_PATH_EXTERNAL, null, SQLiteDatabase.OPEN_READWRITE + SQLiteDatabase.CREATE_IF_NECESSARY);
                try{
                    onCreate(db);
                }catch(Exception e){
                    Log.e("Log",e.getMessage(),e.fillInStackTrace());
                }
                return db;
            }catch(Exception e){
                Log.e("Log",e.getMessage(),e.fillInStackTrace());
                if(db!=null)
                    db.close();
            }
            return db;
        }// End of getWritableDatabase()



**Inserting  and Retrieving data from database:-**


public void insertIntoTable(String[] userName,int[] score)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        try {
            db.beginTransaction();
            for (int i = 0; i < beatID.length; i++) {
                cv.put("UserName",userName[i]);
                cv.put("Score",score[i]);

                db.insert("TableName", "UserName",
                        cv);
            }
            db.setTransactionSuccessful();
        } catch (Exception ex) {

        } finally {
            db.endTransaction();
            db.close();
        }
    }


public void getUserNamePswd(){
        Cursor c = null;
        SQLiteDatabase db = null;
        try{
            db = this.getReadableDatabase();     
            c = db.rawQuery("Select UserName,Score from TableName",null);
            c.moveToFirst();
            String[] username = new String[c.getCount()];
            int[] score = new int[c.getCount()];            
            int counter = 0;
            c.moveToFirst();
            while(!c.isAfterLast()){
            username[counter] = c.getString(0);
            score[counter] = c.getInt(1);
            c.moveToNext();
            counter++;
            }


        }catch(Exception e){
            Log.e("Log", e.getMessage(), e.fillInStackTrace());
            return null;      
        }finally{
            c.close();
            db.close();
        }
    }

其他推荐答案

作为/asset目录是仅读(因为Android .APK文件是仅读取的),因此您不能在资产文件夹文件中写入任何内容,您必须首先复制该SQLITE数据库文件到您的应用程序的内部存储/data/data/<package_name>/databases目录中,您可以修改数据库文件.

  1. 将预先填充的SQLITE数据库文件复制到data/data/<package_name>/databases directory,

  2. 在您的SQLITE数据库助手类中打开该数据库文件(来自/数据库/目录).

  3. 执行插入,更新或选择该数据库的操作.

其他推荐答案

您需要从资产中复制数据库文件,并在/data/data/'''/database/folder

中粘贴
private static String DB_NAME = "QuotesData.db";
private static String DB_PATH = "/data/data/[PACKAGE NAME]/databases/";
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);
        }

        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

在上面的代码中:用您的软件包名称替换[软件包名称].

本文地址:https://www.itbaoku.cn/post/102357.html

问题描述

I have created a SQLite file and putted it on to assets folder. Now I am able to read the data from that file but I don't have any idea how to write to this database file. I need to take the user name and score and store that in to that database file. I searched on the web and on the SO also but there are examples for the normal database insertion.

Can any one tell me how to store the values into database file. I need to store the username and score. Just think this to as Strings and please give me a example for it.

推荐答案

You should not create database in the assets folder as we can only read data from assets folder.

Infact you should create the database in the default internal folder i.e data/data/[package-name]/databases OR you also can create your database in the sdcard and can perform read-write operation but of course it will not run if there is no sdcard.

The following is the code for creating databse in sdcard:-

    private SQLiteDatabase db;
    private static Context cntxt;

    public static File filename = null;
    public static String DATABASE_FILE_PATH_EXTERNAL = null;

    public DBHelper(Context context) {
            super(context, DATABASE_NAME, null,1);
            cntxt = context;
            try{
                try{
                    filename = Environment.getExternalStorageDirectory();
                }catch(Exception e){
                    Toast.makeText(DbHelper.cntxt, "Please Insert SD card To create Database", Toast.LENGTH_LONG).show();
                    Log.e("Log",e.getMessage(),e.fillInStackTrace());
                }

                DATABASE_FILE_PATH_EXTERNAL = filename.getAbsolutePath()+File.separator+DATABASE_NAME;

                //  db = SQLiteDatabase.openDatabase(DATABASE_FILE_PATH_EXTERNAL, null, SQLiteDatabase.OPEN_READWRITE + SQLiteDatabase.CREATE_IF_NECESSARY);
            }catch(Exception e){

                Log.e("Log",e.getMessage(),e.fillInStackTrace());
            }
        }



        @Override
        public synchronized SQLiteDatabase getWritableDatabase() {
            // TODO Auto-generated method stub
            try{
                db = SQLiteDatabase.openDatabase(DATABASE_FILE_PATH_EXTERNAL, null, SQLiteDatabase.OPEN_READWRITE + SQLiteDatabase.CREATE_IF_NECESSARY);
                try{
                    onCreate(db);
                }catch(Exception e){
                    Log.e("Log",e.getMessage(),e.fillInStackTrace());
                }
                return db;
            }catch(Exception e){
                Log.e("Log",e.getMessage(),e.fillInStackTrace());
                if(db!=null)
                    db.close();
            }
            return db;
        }// End of getWritableDatabase()



**Inserting  and Retrieving data from database:-**


public void insertIntoTable(String[] userName,int[] score)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        try {
            db.beginTransaction();
            for (int i = 0; i < beatID.length; i++) {
                cv.put("UserName",userName[i]);
                cv.put("Score",score[i]);

                db.insert("TableName", "UserName",
                        cv);
            }
            db.setTransactionSuccessful();
        } catch (Exception ex) {

        } finally {
            db.endTransaction();
            db.close();
        }
    }


public void getUserNamePswd(){
        Cursor c = null;
        SQLiteDatabase db = null;
        try{
            db = this.getReadableDatabase();     
            c = db.rawQuery("Select UserName,Score from TableName",null);
            c.moveToFirst();
            String[] username = new String[c.getCount()];
            int[] score = new int[c.getCount()];            
            int counter = 0;
            c.moveToFirst();
            while(!c.isAfterLast()){
            username[counter] = c.getString(0);
            score[counter] = c.getInt(1);
            c.moveToNext();
            counter++;
            }


        }catch(Exception e){
            Log.e("Log", e.getMessage(), e.fillInStackTrace());
            return null;      
        }finally{
            c.close();
            db.close();
        }
    }

其他推荐答案

As the /asset directory is read only (because android .apk file is read-only) so you can't write anything in asset folder file, you have to first copy that sqlite database file into your application's internal storage /data/data/<package_name>/databases directory then you can modify your database file..

  1. Copy your pre-populated sqlite database file into data/data/<package_name>/databases directory,

  2. Open that database file (from /databases/ directory) in your sqlite database helper class..

  3. Perform insert, update or select operation on that database..

其他推荐答案

You need to copy database file from asset and paste in /data/data/''/databases/ folder

private static String DB_NAME = "QuotesData.db";
private static String DB_PATH = "/data/data/[PACKAGE NAME]/databases/";
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);
        }

        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

In Above code : Replace [PACKAGE NAME ] with your package name.