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

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

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

  1. private static String DB_PATH = "/data/data/com.example.importDB/databases/";
  2. private static String DB_NAME = "mydb.sql";
  3. private SQLiteDatabase myDataBase;
  4. private final Context myContext;
  5. public DataBaseHelper(Context context) {
  6. super(context, DB_NAME, null, 1);
  7. this.myContext = context;
  8. }
  9. public void createDataBase() throws IOException {
  10. boolean dbExist = checkDataBase();
  11. if(dbExist){
  12. //do nothing - database already exist
  13. }else{
  14. this.getReadableDatabase();
  15. try {
  16. copyDataBase();
  17. } catch (IOException e) {
  18. throw new Error("Error copying database");
  19. }
  20. }
  21. }
  22. private boolean checkDataBase(){
  23. SQLiteDatabase checkDB = null;
  24. try{
  25. String myPath = DB_PATH + DB_NAME;
  26. checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
  27. }catch(SQLiteException e){
  28. //database does't exist yet.
  29. }
  30. if(checkDB != null){
  31. checkDB.close();
  32. }
  33. return checkDB != null ? true : false;
  34. }
  35. private void copyDataBase() throws IOException{
  36. InputStream myInput = myContext.getResources().openRawResource(R.raw.mydb);
  37. String outFileName = DB_PATH + DB_NAME;
  38. OutputStream myOutput = new FileOutputStream(outFileName);
  39. byte[] buffer = new byte[1024];
  40. int length;
  41. while ((length = myInput.read(buffer))>0){
  42. myOutput.write(buffer, 0, length);
  43. }
  44. myOutput.flush();
  45. myOutput.close();
  46. myInput.close();
  47. }
  48. public void openDataBase() throws SQLException {
  49. String myPath = DB_PATH + DB_NAME;
  50. myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
  51. }
  52. @Override
  53. public synchronized void close() {
  54. if(myDataBase != null)
  55. myDataBase.close();
  56. super.close();
  57. }

我的“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那样执行。我也经常看到和做这件事。

相关问题