react-native-sqlite-storage How to open the specified directory file?

1.3k Views Asked by At

my db in: android\app\src\main\assets\app.db

The way i tried:

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

But error:

image

How can i do this?

2

There are 2 best solutions below

0
On BEST ANSWER

run ok!

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

In react-native-cli:

1- It is convenient first of all to make sure that the database exists in the documents directory, with rn-fetch-blob you can list the documents that are in a directory like this:

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


If you do not carry out this step, you can set that a basic database is being created and opened as it does not find any with that name.

You can also open the database from android studio: When Launch succeeded: In Device File Explorer> data> data> com.nameofyourapp> databases You can also click on the bottom tab of android studio 'Database inspector' to see the database changes in real time.

2- Once you are sure that a database already exists in that directory: To open the database in directories inside the cell phone but outside your project: "If your folder is not in app bundle but in app sandbox i.e. downloaded from some remote location"

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