首页 > 解决方案 > react native - 如何使用 sqlite 保存数据?因为出错了

问题描述

我想保存数据字段axios,我需要用 SQLite 来做,但收到警告。有办法解决吗?

就我而言,当我打印 (dbResult) 时我得到了这个:

Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}
Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}
Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}
Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}
Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}

[Unhandled promise rejection: Error: near "Swift": syntax error (code 1 SQLITE_ERROR[1]): , while compiling: INSERT INTO places (artist, image, title, url) VALUES (Taylor Swift, https://images-na.ssl-images-amazon.com/images/I/61McsadO1OL.jpg, Taylor Swift, https://www.amazon.com/Taylor-Swift/dp/B0014I4KH6);]
- node_modules\expo-sqlite\build\SQLite.js:36:15 in _deserializeResultSet
* [native code]:null in map
- node_modules\expo-sqlite\build\SQLite.js:16:40 in SQLiteDatabase#exec
- node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
- node_modules\promise\setimmediate\core.js:123:25 in setImmediate$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:146:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:194:17 in _callImmediatesPass
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:458:30 in callImmediates
* [native code]:null in callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:407:6 in __callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:143:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:142:17 in __guard$argument_0
* [native code]:null in flushedQueue
* [native code]:null in invokeCallbackAndReturnFlushedQueue

在这里我创建了数据库和列:

import * as SQLite from "expo-sqlite";

const db = SQLite.openDatabase('places.db');

export const init = () => {
  const promise = new Promise((resolve, reject) => {
    db.transaction(tx => {
      tx.executeSql(
        'CREATE TABLE IF NOT EXISTS places (id INTEGER PRIMARY KEY NOT NULL, artist TEXT NOT NULL, image TEXT NOT NULL, title TEXT NOT NULL, url TEXT NOT NULL);',
        [],
        () => {
          resolve();
        },
        (_, err) => {
          reject(err);
        }
      );
    });
  });
  return promise;
};

export const insertPlace = (artist, image, title, url) => {
    const promise = new Promise((resolve, reject) => {
        db.transaction(tx => {
          tx.executeSql(
            `INSERT INTO places (artist, image ,title, url) VALUES (${artist}, ${image}, ${title}, ${url});`,
            [],
            (_, result) => {
              resolve(result);
            },
            (_, err) => {
              reject(err);
            }
          );
        });
      });
      return promise;
};

export const fetchPlaces = () => {
    const promise = new Promise((resolve, reject) => {
        db.transaction(tx => {
          tx.executeSql(
            'SELECT * FROM places',
            [],
            (_, result) => {
              resolve(result);
            },
            (_, err) => {
              reject(err);
            }
          );
        });
      });
      return promise;
};

在这里我使用axios.get来获取数据,然后使用该insertPlace函数将字段数据保存到places.db我创建的列中,但正如我提到的那样出现错误,我不明白我的问题。


import axios from "axios";
import { insertPlace } from "../helpers/db";

export default class WaterQualitySamplesScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  getData = () => {
    axios
      .get("https://rallycoding.herokuapp.com/api/music_albums")
      .then((res) => {
        this.setState({
          data: res.data,
        });
        //  console.log(res.data);
        for (let i = 0; i < res.data.length; i++) {
          const mediaData = res.data[i];

            const dbResult =  insertPlace(
              mediaData.artist,
              mediaData.image,
              mediaData.title,
              mediaData.url
            );
            console.log(dbResult);

        }
      });
  };

async componentDidMount() {
    this.currentUser = await firebase.auth().currentUser;
    await this.registerForPushNotificationsAsync();

    this.getData();
  }

render() {
    return (
    ),
  };
};

标签: javascriptreactjsreact-nativeexpo

解决方案


  getData = () => {
    axios
      .get("https://rallycoding.herokuapp.com/api/music_albums")
      .then((res) => {
        this.setState({
          data: res.data,
        });
        //  console.log(res.data);
        for (let i = 0; i < res.data.length; i++) {
          const mediaData = res.data[i];

            const dbResult =  insertPlace(
              mediaData.artist,
              mediaData.image,
              mediaData.title,
              mediaData.url
            );
            console.log(dbResult);

        }
      })
     .catch(err => console.log(err))          // this is the catch
  };

也可能是缺少 .then() 来解决问题。


推荐阅读