如何在React Native中将初始数据(主数据)插入SQLite?

时间:2019-07-27 15:58:25

标签: sqlite react-native expo

我挑战将主数据插入React Native中的SQLite中。 但是,每次我启动应用程序时,数据都会插入到SQLite表中。

1 个答案:

答案 0 :(得分:0)

模块允许访问数据库交易,以便将数据放置在数据库存储库中。

,您可以使用 AsyncStorage

示例

import {AsyncStorage} from 'react-native';
import { openDatabase } from 'react-native-sqlite-storage';
let db = openDatabase({ name: 'openDatabase.db' });
...
  register_user = async () => {
    const { user_name } = this.state;
    const { user_address } = this.state;
    if (user_name) {
        if (user_address) {
          db.transaction(function(tx) {
            tx.executeSql(
              'INSERT INTO table_user (user_name, user_address) VALUES (?,?,?)',
              [user_name, user_address],
              (tx, results) => {
                console.log('Results', results.rowsAffected);
                if (results.rowsAffected > 0) {
                  await AsyncStorage.setItem('First',true);
                  Alert.alert(
                    'Success',
                    'You are Registered Successfully'
                  );
                } else {
                  alert('Registration Failed');
                }
              }
            );
          });
        } else {
          alert('Please fill Address');
        }
    } else {
      alert('Please fill Name');
    }
  };

async componentDidmount(){
 const check = await AsyncStorage.getItem('First');
  if(check !== true) {
    this.register_user();
  }
}