【问题标题】:react-native-sqlite-storage How to open the specified directory file?react-native-sqlite-storage 如何打开指定目录的文件?
【发布时间】:2020-03-27 18:30:45
【问题描述】:

我的数据库在:android\app\src\main\assets\app.db

我尝试的方式:

  open() {
    SQLiteStorage.DEBUG(true);
    SQLiteStorage.openDatabase({
      name: 'file:///android_asset/app.db',
    })
      .then(() => {
        console.info('');
      })
      .catch(err => {
        console.warn(err);
      });
  }

但是错误:

我该怎么做?

【问题讨论】:

    标签: sqlite react-native react-native-android react-native-sqlite-storage


    【解决方案1】:

    在 react-native-cli 中:

    1- 首先确保数据库存在在文档目录中很方便,使用 rn-fetch-blob 您可以列出目录中的文档,如下所示:

    import RNFetchBlob from 'rn-fetch-blob';
    
    
    
    let dirs = RNFetchBlob.fs.dirs;
    const documentPath = dirs.DocumentDir;
    const externalZipPath = dirs.DCIMDir;
          
    
    RNFetchBlob.fs.ls (documentPath) .then ((files) => {
     console.log (files)
     })
    
    
    

    如果您不执行此步骤,您可以设置正在创建和打开一个基本数据库,因为它没有找到任何具有该名称的数据库。

    您可以也可以从 android studio 打开数据库: 启动成功时: 在设备文件资源管理器> 数据> 数据> com.nameofyourapp> 数据库中 您也可以点击android studio 'Database inspector' 的底部标签,实时查看数据库的变化。

    2- 一旦您确定该目录中已存在数据库: 在手机内但项目外的目录中打开数据库: “如果您的文件夹不在应用程序包中,而是在应用程序沙箱中,即从某个远程位置下载”

    let openDbExample = () => {
    
        let errorCB = (err) => {
              console.log ("SQL Error:" + err);
            }
          
        let successCB = () => {
        db.transaction ((tx) => {
        tx.executeSql (
        `SELECT * FROM name_column_table LIMIT 10`, [], (tx, results) => {
        var len = results.rows.length;
    
                for (let i = 0; i <len; i ++) {
                    let row = results.rows.item (i);
                    console.log (row);
                }
            })
         })
        }
    
      if (Platform.OS === 'ios') {
      db = SQLite.openDatabase ({name: "example_data_base.db", location: 
      'Documents'}, successCB, errorCB);
      } 
      else {
      db = SQLite.openDatabase ({name: "example_data_base.db", readOnly: true, 
      location: "default", createFromLocation: 2}, successCB, errorCB)
      }
    }
    

    【讨论】:

      【解决方案2】:

      运行正常!

       open() {
          SQLiteStorage.DEBUG(true);
          SQLiteStorage.openDatabase({
            name: 'app.db', // android/app/src/main/assets/app.db
          })
            .then(() => {
              console.info('');
            })
            .catch(err => {
              console.warn(err);
            });
        }
      

      【讨论】:

        猜你喜欢
        • 2017-12-14
        • 2017-10-31
        • 2019-07-15
        • 2022-08-09
        • 2017-06-18
        • 1970-01-01
        • 2020-03-15
        • 1970-01-01
        • 2019-12-03
        相关资源
        最近更新 更多