React native,如何导入react-native-sqlite-storage库

6mzjoqzu  于 2023-04-30  发布在  SQLite
关注(0)|答案(1)|浏览(195)

我按照下面的说明使用sqlLite与准备好的数据库文件
www.example. com
我可以在Xcode中设置没有任何问题,但我不能正确导入JS文件中的库。

import SQLite from 'react-native-sqlite-storage';
console.log(SQLite) // {}

SQLLite是空对象。因此,没有openDatabase方法。
图书馆的版本是

"react-native-sqlite-storage": "^6.0.1",
"react": "18.2.0",
"react-native": "0.71.7",

我做错了什么?

wfveoks0

wfveoks01#

在新版本的文档中,它没有更新,但你可以像下面提到的那样使用。

import { openDatabase } from 'react-native-sqlite-storage';

const createTable = ({ dbName, tableName, query }) => {
  const db = openDatabase({ name: dbName });

  db.transaction((txn) => {
    txn.executeSql(
      `SELECT name FROM sqlite_master WHERE type='table' AND name='${tableName}'`,
      [],
      (tx, result) => {
        if (result?.rows?.length === 0) {
          txn.executeSql(`DROP TABLE IF EXISTS ${tableName}`, []);
          txn.executeSql(
            query,
            []
          );
          console.log(`DataBase ${dbName} with table name ${tableName} is created successfully`);
        } else {
          console.log(`DataBase ${dbName} with table name ${tableName} is already exists`);
        }
      },
      ({ message }) => console.log('Error caught while creating table', message)
    );
  });
};

然后使用下面的函数插入数据

const insertDataInTable = ({ dbName, tableName, query, values }) => {
  const db = openDatabase({ name: dbName });

  db.transaction((txn) => {
    txn.executeSql(
      query,
      values,
      (tx, result) => {
        console.log('result: ', result);
        for (let i = 0; i < result?.rows?.length; ++i) {
          console.log(`Data inserted into table '${tableName}' - `, result?.rows?.item(i));
        }
      },
      ({ message }) => console.log('Error caught while inserting data in table', message)
    );
  });
};

相关问题