在android应用程序中导入sql脚本

jv2fixgn  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(339)

我有一个mysql脚本,我的数据库,我想导入这个数据库到我的android应用程序使用该脚本,当我执行这个代码它的作品(我不知道)´没有任何异常或错误),但当我试图从数据库获取信息时,它没有´不起作用。

private static String DB_PATH = "/data/data/com.example.importDB/databases/";
    private static String DB_NAME = "mydb.sql";
    private SQLiteDatabase myDataBase;
    private final Context myContext;

    public DataBaseHelper(Context context) {
        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }

    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();
        if(dbExist){
            //do nothing - database already exist
        }else{
            this.getReadableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    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;
    }

    private void copyDataBase() throws IOException{
        InputStream myInput = myContext.getResources().openRawResource(R.raw.mydb);
        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();

    }

    public void openDataBase() throws SQLException {
        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();
    }

我的“mydb.sql”在res/raw文件夹中
这是mysql脚本:
https://mega.nz/#!kuka0jry!r2bsqwmjbtmxgtab1dzvpg-juoehy9oifg3k4ohk公司
谢谢

pjngdqdw

pjngdqdw1#

您正在复制sql脚本,然后将其用作数据库。这行不通。
你需要在android中创建一个新的db。然后有几个选项可以运行脚本sql:
1) 如果将其保存在文件中很重要,您可以找到类似scriptrunner的工具(http://gulvaniharesh.blogspot.com/2013/08/import-sql-script-of-mysql-from-java.html)-我没用过,但安卓没有这种功能。
2) 将sql脚本移动到创建db时执行的静态字符串。我已经看过很多次了。
3) 将sql脚本移到xml资源中,然后像上面的#2那样执行。我也经常看到和做这件事。

相关问题