如何将sqlite与react-native一起使用?

时间:2018-05-01 15:21:06

标签: javascript react-native sqlite local-storage

我正在使用react-native app,现在正在使用SQLite实现持久数据存储。我遵循文档,但它不起作用。

我将数据库存储在android / app / src / main / assets / test.db

没有错误,但没有显示任何内容。

这是我实现的代码

let SQLite = require('react-native-sqlite-storage')

class HomeScreen extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      sqliteData: [],
     };
    let db = SQLite.openDatabase({name: 'test.db', createFromLocation : "~test.db", location: 'Library'}, this.openCB, this.errorCB);
    db.transaction((tx) => {
     tx.executeSql('SELECT * FROM testTable', [], (tx, results) => {
      var len = results.rows.length;
      var rows = []
        for (var i = 0; i < len.length; i++) {
          var row = results.rows.item(i);
          rows.push(row)
          console.log(row + row.userName)
        }
        this.setState({sqliteData: rows});
     }) 
    })
  }

  errorCB(err) {
    console.log("SQL Error: " + err);
  }

  successCB() {
    console.log("SQL executed fine");
  }

  openCB() {
    console.log("Database OPENED");
  }

  render(){
     return(
        <Flatlist>--showing all items--</Flatlist>
     )
  }

}

2 个答案:

答案 0 :(得分:0)

我创建了一个工作演示,只需检查一下!

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,TouchableOpacity, TextInput,ListView,ActivityIndicator
} from 'react-native';


import Sqlite from './AppComponent/SqliteHelper';
let SQLiteStorage = require('react-native-sqlite-storage')


var TAG = "App : ";
var records = [];
var _this = null;
var db = null;

export default class App extends Component<{}> {

  constructor() {
    super();
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows([]),
      selected :0,
      itemNo:'',
      itemName:'',
      records :[],
      loading:false,
    };
    _this = this;
  }

  componentWillMount(){
    console.log(TAG + "-----componentWillMount-----")
    Sqlite.initialize();
  }

 /**
  * List item row UI
  * @param {*} rowData 
  */
  listRowItems(rowData) {
    console.log(TAG + "-----listRowItems------")
    if (rowData != null) {
      return <View style={styles.listItemStyle}>
                <Text>ItemNo:{rowData.ITEMNO}</Text>
                <Text>ItemName:{rowData.ITEMNAME}</Text>
                <View style={{marginTop:5,marginBottom:5,backgroundColor:'#000',height:1}}/>
              </View>
    } else {
      console.log(TAG + "rowdata null")
    }
  }

 /**
  * UI modification while selecting diff options
  * @param {*} value 
  */
  changeSelection(value){
    this.setState({selected:value});
  }

  /**
   * When click on google
   */
  goClick(){
    console.log(TAG + "------goClick----")
    switch(this.state.selected){
      case 0:
              this.SearchItemWithInsert(this.state.itemNo,this.state.itemName);
              break;
      case 1:
              this.SearchWithUpdate(this.state.itemNo,this.state.itemName)
              break;
      case 2:
              this.SearchWithDelete(this.state.itemNo)
              break;
      case 3:
              this.searchRecord(this.state.itemNo)
              break;
      case 4:
              this.deleteAllRecords();
              break;
      case 5:              
              this.getAllItems();
              break;

    }
  }

  /**
   * update record
   * @param {*} ITEMNO 
   * @param {*} ITEMNAME 
   */
  updateItemName(ITEMNO, ITEMNAME) {
    console.log(TAG + "-----updateItemName------");

        _this.startLoading();
        var query = "UPDATE Table1 set ITEMNAME='" + ITEMNAME + "' where ITEMNO =" + ITEMNO;
        console.log(TAG + "query : " + query);
        db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);        
        try {
          db.transaction((tx) => {
            tx.executeSql(query, [], (tx, results) => {
              console.log(TAG + "Item updated...");
              _this.getAllItems();
            }, function (error) {
              _this.stopLoading()
              console.log(TAG + "Item update error: " + error.message);
            });
          });
        } catch (ex) {
          console.log(TAG + "error in updateITEMNAME " + JSON.stringify(ex));
        }

  }

  /**
   * before delete search record, if found then delete record
   * @param {*} ITEMNO 
   */
  SearchWithDelete(ITEMNO) {
    console.log(TAG + "-----SearchWithDelete------");
    if (ITEMNO.length > 0) {
      _this.startLoading();
      db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);
      db.transaction((tx) => {
        tx.executeSql('SELECT * FROM Table1 where ITEMNO=' + ITEMNO, [], (tx, results) => {
          console.log(TAG + "results :" + JSON.stringify(results))
          var len = results.rows.length;
          console.log(TAG + "Items found : " + len);
          if (len > 0) {
            _this.DeletesItem(ITEMNO);
          } else {
            _this.stopLoading()
            alert('Not found')
          }
        }, function (error) {
          _this.stopLoading()
          console.log(TAG + "Item delete error: " + error.message);
        });
      });
    } else {
      _this.stopLoading()
      alert('please enter item no')
    }
  }

  /**
   * delete record
   * @param {*} ITEMNO 
   */
  DeletesItem(ITEMNO) {
    console.log(TAG + "-----DeletesItem------");
    db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);
    db.transaction((txn) => {
      txn.executeSql('DELETE FROM Table1 where ITEMNO =' + ITEMNO, [], (txn, resultsN) => {
        console.log(TAG + "deleted 1 Item");
        _this.getAllItems()
      }, function (error) {
        _this.stopLoading()
        console.log(TAG + "Item delete error: " + error.message);
      });
    });
  }

  /**
   * search record, if found update it
   * @param {*} ITEMNO 
   * @param {*} ITEMNAME 
   */
  SearchWithUpdate(ITEMNO, ITEMNAME) {
    console.log(TAG + "-----SearchWithUpdate------");
    if (ITEMNO.length > 0) {
      if (ITEMNAME.length > 0) {
        _this.startLoading();
        db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);
        db.transaction((tx) => {
          tx.executeSql('SELECT * FROM Table1 where ITEMNO=' + ITEMNO, [], (tx, results) => {
            console.log(TAG + "results :" + JSON.stringify(results))
            var len = results.rows.length;
            console.log(TAG + "Items found : " + len);
            if (len > 0) {
              _this.updateItemName(ITEMNO, ITEMNAME);
            } else {
              _this.stopLoading()
              alert('Not found')
            }
          });
        });
      } else {
        _this.stopLoading()
        alert('please enter item name')
      }
    } else {
      _this.stopLoading()
      alert('please enter item no')
    }
  }

  /**
   * search record, if not found then insert it
   * @param {*} ITEMNO 
   * @param {*} ITEMNAME 
   */
  SearchItemWithInsert(ITEMNO, ITEMNAME) {
    console.log(TAG + "-----SearchItem------");
    if (ITEMNO.length > 0) {
      if (ITEMNAME.length > 0) {
        _this.startLoading();
        db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);
        db.transaction((tx) => {
          tx.executeSql('SELECT * FROM Table1 where ITEMNO=' + ITEMNO, [], (tx, results) => {
            console.log(TAG + "results :" + JSON.stringify(results))
            var len = results.rows.length;
            console.log(TAG + "Items found : " + len);
            if (len > 0) {
              _this.stopLoading()
              alert('already available')
            } else {
              _this.insertIntoItemTable(ITEMNO, ITEMNAME);
            }
          }, function (error) {
            _this.stopLoading()
            console.log(TAG + "Item insert error: " + error.message);
          });
        });
      } else {
        _this.stopLoading()
        alert('please enter item name')
      }
    } else {
      _this.stopLoading()
      alert('please enter item no')
    }
  }

  /**
   * Insert function
   * @param {*} ITEMNO 
   * @param {*} ITEMNAME 
   */
  insertIntoItemTable(ITEMNO, ITEMNAME) {
    console.log(TAG + "-------insertIntoItemTable---------")

        try {         
          var query = 'INSERT INTO Table1 ( ITEMNO,ITEMNAME ) VALUES (?,?)';
          db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);
          db.transaction((tx) => {
            tx.executeSql(query,
              [ITEMNO, ITEMNAME],
              (tx, results) => {
                console.log(TAG + "Item  : " + ITEMNAME + ' inserted......');
                _this.getAllItems();
              }, function (error) {
                console.log(TAG + "Item  : " + ITEMNAME + ' insertion error: ' + error.message);
              });
          });
        } catch (ex) {
          console.log(TAG + "Exception: " + ex);
        }

  }

  startLoading(){
    console.log(TAG + '------startLoading-----')
    this.setState({loading:true})
  }


  stopLoading(){
    console.log(TAG + '------stopLoading-----')
    this.setState({loading:false})
  }

  /**
   * search record
   * @param {*} ITEMNO 
   */
  searchRecord(ITEMNO) {
    console.log(TAG + '-----searchRecord-----');
    if (ITEMNO.length > 0) {
      this.startLoading();
      db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);
      db.transaction((tx) => {
        tx.executeSql('SELECT * FROM Table1 where ITEMNO=' + ITEMNO, [], (tx, results) => {
          console.log(TAG + "Query completed");
          // Get rows with Web SQL Database spec compliance.
          var len = results.rows.length;
          console.log(TAG + 'len::::::' + len);
          var aryData = [];
          for (let i = 0; i < len; i++) {
            let row = results.rows.item(i);
            console.log(TAG + `Record:::::::: ${row.ITEMNO} ${row.ITEMNAME}`);
            aryData.push({ ITEMNO: row.ITEMNO, ITEMNAME: row.ITEMNAME });
          }
          console.log(TAG + 'arydata :: ' + JSON.stringify(aryData));
          if (aryData.length == 0) {
            _this.stopLoading()
            alert('no record found')
          } else {
          _this.populateList(aryData);
          }
        });
      });
    } else {
      alert('enter item no')
    }
  }

  /**
   * load all items/records from database
   */
  getAllItems(){
    console.log(TAG + '-----getAllItems-----');  
    this.startLoading();  
    db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);
    db.transaction((tx) => {
      tx.executeSql('SELECT * FROM Table1', [], (tx, results) => {
          console.log(TAG + "Query completed");
          // Get rows with Web SQL Database spec compliance.
          var len = results.rows.length;
          console.log(TAG + 'len::::::' + len);
          var aryData = [];
          for (let i = 0; i < len; i++)
          {
            let row = results.rows.item(i);
            console.log(TAG + `Record:::::::: ${row.ITEMNO} ${row.ITEMNAME}`);
            aryData.push({ITEMNO:row.ITEMNO,ITEMNAME:row.ITEMNAME});
          }
          console.log(TAG + 'arydata :: ' + JSON.stringify(aryData));
        if (aryData.length == 0) {
          _this.stopLoading()
          alert('no record found')
        } else {
          _this.populateList(aryData);
        }
      });    
    });
  }

  /**
   * attach all data fetched from database to listview
   * @param {*} aryData 
   */
  populateList(aryData){    
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    var dataSourceTemp = ds.cloneWithRows(aryData);
    this.setState({records:aryData,dataSource:dataSourceTemp});
    _this.stopLoading()

  }

  /**
   * delete all records
   */
  deleteAllRecords(){
    console.log(TAG + "-----deleteAllRecords------");
    db = SQLiteStorage.openDatabase("DemoDB", '1.0', '', 1);
    db.transaction((txn) => {
        txn.executeSql('DELETE FROM Table1', [], (txn, resultsN) => {
            console.log(TAG + "deleted 1 Item");
            this.getAllItems();
        });
    });
  }

  render() {
    return (

        (this.state.loading)?<View style={styles.containerholder}>
          <View style={styles.containerloading}>
            <ActivityIndicator color='grey' size="large" color="#0000ff" />
          </View>
        </View>
        :       
        <View style={styles.container}>
        <View style={styles.buttonContainer}>
          <TouchableOpacity onPress={()=>this.changeSelection(0)} style={(this.state.selected == 0)?styles.buttonStyleSelected:styles.buttonStyle}>
            <Text style={(this.state.selected == 0)?styles.buttonTextSelected:styles.buttonText}>Insert single</Text>
          </TouchableOpacity>

          <TouchableOpacity onPress={()=>this.changeSelection(1)} style={(this.state.selected == 1)?styles.buttonStyleSelected:styles.buttonStyle}>
            <Text style={(this.state.selected == 1)?styles.buttonTextSelected:styles.buttonText}>Update single</Text>
          </TouchableOpacity>

          <TouchableOpacity onPress={()=>this.changeSelection(2)} style={(this.state.selected == 2)?styles.buttonStyleSelected:styles.buttonStyle}>
            <Text  style={(this.state.selected == 2)?styles.buttonTextSelected:styles.buttonText}>Delete single</Text>
          </TouchableOpacity>

          <TouchableOpacity onPress={()=>this.changeSelection(3)} style={(this.state.selected == 3)?styles.buttonStyleSelected:styles.buttonStyle}>
            <Text  style={(this.state.selected == 3)?styles.buttonTextSelected:styles.buttonText}>search</Text>
          </TouchableOpacity>
        </View>  

        <View style={styles.buttonContainer}>
          <TouchableOpacity onPress={()=>this.changeSelection(4)} style={(this.state.selected == 4)?styles.buttonStyleSelected:styles.buttonStyle}>
            <Text  style={(this.state.selected == 4)?styles.buttonTextSelected:styles.buttonText}>All Delete</Text>
          </TouchableOpacity>

          <TouchableOpacity onPress={()=>this.changeSelection(5)} style={(this.state.selected == 5)?styles.buttonStyleSelected:styles.buttonStyle}>
            <Text style={(this.state.selected == 5)?styles.buttonTextSelected:styles.buttonText}>Refresh record</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.formStyle}>
          {((this.state.selected == 4) || (this.state.selected == 5))?null:
          <View>
            <Text>Item No</Text>
            <TextInput keyboardType = {'numeric'} style = {styles.textInputstyle} onChangeText = {(text) => this.setState({itemNo:text})} value = {this.state.itemNo}/>
          </View>
          }

          {((this.state.selected == 2) || (this.state.selected == 3) || (this.state.selected == 4) || (this.state.selected == 5))?null:
            <View style={{marginTop:10}}>
              <Text>Item Name</Text>
              <TextInput style = {styles.textInputstyle} onChangeText = {(text) => this.setState({itemName:text})} value = {this.state.itemName}/>
            </View>
          }

          <View>
            <TouchableOpacity style={styles.goStyle} onPress={()=>this.goClick()}>
              <Text style={{color:'#fff'}}>GO</Text>
            </TouchableOpacity>
          </View>
        </View>

        <ListView
          style={{flex:1}}
          dataSource={this.state.dataSource}
          renderRow={(rowData) => this.listRowItems(rowData)}
          enableEmptySections ={true}/>                             
      </View>

    );
  }
}

const styles = StyleSheet.create({
  containerloading: {    
    justifyContent: 'center',    
    height:150,
    width:150,    
  },
  containerholder: {
    flex: 1,    
    backgroundColor: 'rgba(255, 255, 255, .4)',
    justifyContent: 'center', 
    alignItems:'center',
  },
  container: {
    flex: 1,    
    backgroundColor: '#fff',
    padding:10,
  },
  buttonContainer:{
    flexDirection:'row', 
    marginTop:10,
    marginBottom:10,   
  },
  buttonStyleSelected:{
    padding:5,
    backgroundColor:'#00ff',    
    marginLeft:5,
  },
  buttonStyle:{
    padding:5,
    backgroundColor:'gray',    
    marginLeft:5,    
  },
  buttonText :{
    color:'#000',
  },
  buttonTextSelected :{
    color:'#fff',
  },
  formStyle:{
    borderRadius: 4,
    borderWidth: 0.5,
    borderColor: '#000',
    padding:15,
  },
  textInputstyle:{    
      height: 40,
      width:100,
      borderColor: 'gray',
      borderWidth: 1 ,
      marginTop:10,   
  },
  goStyle:{
    padding:5,
    backgroundColor:'gray',    
    width:100,    
    marginTop:15, 
    justifyContent: 'center',
    alignItems: 'center',
  },
  listItemStyle:{
    padding:10,
  }

});

答案 1 :(得分:0)

您需要安装npm install expo-sqlite,然后再安装 您需要创建一个SQLite数据库并将其存储在您的项目根文件夹中,然后尝试以下代码示例

    import React from 'react';
import { StyleSheet, Text, View,FlatList,Alert} from 'react-native';
import { TextInput,Button,IconButton,Colors } from 'react-native-paper';
import { SQLite } from 'expo-sqlite';
const db = SQLite.openDatabase('test.db');



class UsersScreen extends React.Component 
{   

    constructor(props) {
        super(props);
        this.state = {
          FlatListItems: [],
        };
        db.transaction(tx => {
          tx.executeSql('SELECT * FROM users', [], (tx, results) => {
            var temp = [];
            for (let i = 0; i < results.rows.length; ++i) {
              temp.push(results.rows.item(i));
            }
            this.setState({
              FlatListItems: temp,
            });
          });
        });
      }


    ListViewItemSeparator = () => {
        return (
          <View style={{ height: 0.2, width: '100%', backgroundColor: '#808080' }} />
        );
      };



    render()
    {
            return(
                <View>
                <FlatList
                  data={this.state.FlatListItems}
                  ItemSeparatorComponent={this.ListViewItemSeparator}
                  keyExtractor={(item, index) => index.toString()}
                  renderItem={({ item }) => (

                    <View key={item.userid} style={{ backgroundColor: 'white', padding: 20 }}>
                      <Text>Id: {item.userid}</Text>
                      <Text>Name: {item.firstname }</Text>
                      <Text>UserName: {item.username }</Text>
                      <Text>Email: {item.email}</Text>
                      <Text>Password: {item.password}</Text>
                      <Button icon="person-add" mode="contained" style={styles.buton} onPress={() => this.props.navigation.navigate("DeleteUser",{"UserId":item.userid})}>  Delete User </Button>
                      <Button icon="person-add" mode="contained" style={styles.buton} onPress={() => this.props.navigation.navigate("EditUser",{"UserId":item.userid})}>  Edit User </Button>

                    </View>
                  )}
                />
              </View>
            );
    }

}

const styles = StyleSheet.create({
    container: {
      backgroundColor: '#fff',
    },
    textinput:{
      marginLeft:5,
      marginLeft:5,
      backgroundColor: 'transparent'
    },
    buton:{
      margin:10,
      marginBottom:10,
      backgroundColor: '#f05555'
    }  

  });

export default UsersScreen;

此代码是我的React Native App的一部分。 编码愉快。 :)