簡體   English   中英

我怎樣才能將sqlite與react-native一起使用?

[英]How can I use sqlite with react-native?

我正在使用react-native應用程序,現在使用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>
     )
  }

}

我已經創建了一個工作演示,只需檢查一下即可!

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,
  }

});

您需要安裝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的一部分。 編碼愉快。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM