如何设置从sqlite db表重试的结果到本机的数组?

时间:2017-07-27 12:54:44

标签: sqlite react-native-android

这是我的代码

var employeeList = [] ;
let db = SQLite.openDatabase({name: 'test.db', createFromLocation : "~example.db", location: 'Library'}, false,false);

db.transaction((tx) => {     
  tx.executeSql('SELECT * FROM Employees', [], (tx, results) => {      
      console.log("Query completed");
      var len = results.rows.length;
      for (let i = 0; i < len; i++) {
        let row = results.rows.item(i); 
        employeeList.push(row.name);        
      }
      this.setState({employees:employeeList});   
        db.closeDatabase();       
    });
});
alert(this.state.employees);

我能够在事务中将结果设置为employeeList。但是当我在事务外检查employeeList时,它变得空白...... 我需要做什么才能将results.row设置为employees对象..

2 个答案:

答案 0 :(得分:0)

这是异步的。在执行数据库事务之前,您需要一个值。您需要使用promises或回调来了解查询何时执行。

答案 1 :(得分:0)

正如加百列提到的那样,您需要将通话包装在Promise中。我提供了一个示例,说明您可能想怎么做。

    const getEmployees = new Promise(function(resolve, reject) {
    var employeeList = [] ;
    let db = SQLite.openDatabase({name: 'test.db', createFromLocation : "~example.db", location: 'Library'}, false,false);

    db.transaction((tx) => {     
    tx.executeSql('SELECT * FROM Employees', [], (tx, results) => {      
        console.log("Query completed");
        var len = results.rows.length;
        for (let i = 0; i < len; i++) {
            let row = results.rows.item(i); 
            employeeList.push(row.name);        
        }
        db.closeDatabase();

        // resolve promise
        resolve(employeeList)
    });
});

getEmployees.then(data => {
    this.setState({
        employees:employeeList
    })
})