如何在SQLite中记录错误回调?

时间:2018-04-12 01:27:40

标签: sqlite react-native

我正在尝试使用以下代码连接到数据库:

import SQLite from 'react-native-sqlite-storage'

var db = SQLite.openDatabase({name : "banco.db", createFromLocation : 1}, this.successCB(), this.errorCB());

errorCB() {
  this.setState({message: "I NEED SHOW THE ERROR HERE"});
} 

successCB() {
  this.setState({message: "SQL executed fine"});
}

如何在errorCB函数上显示错误?

2 个答案:

答案 0 :(得分:1)

这是the documentation example。错误回调将传递包含错误的参数。您也没有向openDatabase提供正确的值。你应该传递函数,而不是试图调用函数。

从文档中复制粘贴相关部分并附注释:

// Your error callback function that should take an argument that will contain your error.
errorCB(err) {
  console.log("SQL Error: " + err);
  // Here you can use err in your setState call.
}

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

// openDatabase should be passed in the functions; openCB and errorCB in this example.
var db = SQLite.openDatabase("test.db", "1.0", "Test Database", 200000, openCB, errorCB);

// What you're doing is incorrect as it's akin to doing this which is wrong.
// var db = SQLite.openDatabase("test.db", "1.0", "Test Database", 200000, openCB(), errorCB());

这实际上是一个基本的JavaScript问题,您需要能够阅读文档并了解如何使用给定的API。如果您遇到此问题,我建议您阅读Higher-Order Functions,因为它是JavaScript的基础。

编辑:非常直接并回答评论;这就是你的代码应该是这样的:

import SQLite from 'react-native-sqlite-storage'

var db = SQLite.openDatabase({name : "banco.db", createFromLocation : 1}, this.successCB, this.errorCB);

// Making the assumption that these are in a class,
// otherwise add the const keyword before them.
// Convert these to arrow functions instead
// so they can more easily be passed as variables.
errorCB = (err) => {
  this.setState({message: err});
}

successCB = () => {
  this.setState({message: "SQL executed fine"});
}

鉴于你的意见,我在这里会非常直接。如果您不了解JavaScript中的函数,高阶函数和变量/值如何工作,那么使用React Native将会非常困难。特别是如果您不熟悉ES6语法。在处理React Native之前,请阅读该链接中的书籍或其他许多用于学习JavaScript基础知识的资源。

答案 1 :(得分:1)

我曾经使用以下语句

打开SQLite
database = SQLite.openDatabase({name: 'my.db', location: 'default'}, (db) => {
     db.transaction( tx => {
     tx.executeSql(`CREATE TABLE IF NOT EXISTS tableName (columnNames)`);
        }, error => {
           this.setState({message: error});
     });
 }, error => {
    this.setState({message: error});
});

希望这会有所帮助!