与SQLite数据库的React Native连接

时间:2017-03-07 18:23:40

标签: javascript android react-native

我是React Native的新手,我想知道我是否可以连接本地SQLite数据库文件(.db)我遵循Github上的一些指南,但它对我不起作用,还有其他方法去做吧?? (使用Android)

以下是我所说的指南:https://github.com/andpor/react-native-sqlite-storage

1 个答案:

答案 0 :(得分:0)

global.db = SQLite.openDatabase(
  {
    name: "silkyMarket",
    location: "default",
    createFromLocation: "~SQLite.db",
  },
  () => {},
  (error) => {
    console.log("ERROR: " + error);
  }
);
function SettingsScreen() {
  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      <Text>Settings!</Text>
    </View>
  );
}

将其添加到您的应用程序的入口文件中,例如 index.js 的 app.js,然后您可以在其他文件中访问它,如下所示:

import React from "react";
import SQLite from "react-native-sqlite-storage";

export default class SQLiteScreen extends React.Component {
  constructor() {
    super();
    SQLite.DEBUG = true;
  }

  ExecuteQuery = (sql, params = []) =>
    new Promise((resolve, reject) => {
      db.transaction((trans) => {
        trans.executeSql(
          sql,
          params,
          (trans, results) => {
            resolve(results);
          },
          (error) => {
            reject(error);
          }
        );
      });
    });

  // Create Table
  async CreateTable() {
    let Table = await this.executeQuery(
      "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY NOT NULL, first_name VARCHAR(16), last_name VARCHAR(16), is_deleted INTEGER)",
      []
    );
    console.log(Table);
  }
}