我遵循从现有数据库中为iOS填充值的所有说明:link
使用以下代码:
import SQLite from 'react-native-sqlite-storage';
var db;
export default class App extends Component<Props> {
errorCB(err) {
console.log("SQL Error: " + err);
};
successCB() {
console.log("SQL executed fine");
};
openCB() {
console.log("Database OPENED");
};
openDB() {
db = SQLite.openDatabase({name : "sqliteexample", createFromLocation : 1}, this.openCB, this.errorCB);
}
populateDB() {
db.transaction((tx) => {
tx.executeSql("SELECT * FROM Users", [], (tx, results) => {
console.log("Query completed");
// Get rows with Web SQL Database spec compliance.
var len = results.rows.length;
console.log('len' + len)
for (let i = 0; i < len; i++) {
let row = results.rows.item(i);
console.log(`User: ${row}`);
}
});
});
}
render() {
return (
<View style={styles.container} >
<Button onPress={this. openDB}
title="open Database"
color="#841584"/>
<Button onPress={this. populateDB}
title="Get Data"
color="#841584"/>
</View>
);
}
}
我收到此错误:
undefined不是对象(评估'db.transaction')
但是在控制台中成功打开数据库获取以下消息:
2018-06-08 11:43:40.678 [info] [tid:com.facebook.react.SQLiteQueue] [SQLite.m:255] open cb 结束了2018-06-08 11:43:40.679 [info] [tid:com.facebook.react.JavaScript] DB打开:sqliteexample 2018-06-08 11:43:40.679165 + 0530 FlatListAppDemo [1018:61832] open cb 完成确定2018-06-08 11:43:40.679220 + 0530 FlatListAppDemo [1018:61820] DB已打开:sqliteexample
请帮我解决这个问题。 提前谢谢。
答案 0 :(得分:0)
您可以尝试这样
import SQLite from 'react-native-sqlite-storage';
var database_name = "sqliteexample"; // Add your Database name
var database_version = "1.0"; // Add your Database Version
var database_size = 200000; // Add your Database Size
var database_displayname = "SQL Database"; // Add your Database Displayname
var db;
export default class App extends Component<Props> {
errorCB(err) {
console.log("SQL Error: " + err);
};
successCB() {
console.log("SQL executed fine");
};
openCB() {
console.log("Database OPENED");
};
openDB() {
db = SQLite.openDatabase(database_name, database_version, database_displayname, database_size, this.openCB, this.errorCB);
}
populateDB() {
db = SQLite.openDatabase(database_name, database_version, database_displayname, database_size, this.openCB, this.errorCB);
db.transaction((tx) => {
tx.executeSql("SELECT * FROM Users", [], (tx, results) => {
console.log("Query completed");
// Get rows with Web SQL Database spec compliance.
var len = results.rows.length;
console.log('len' + len)
for (let i = 0; i < len; i++) {
let row = results.rows.item(i);
console.log(`User: ${row}`);
}
});
});
}
render() {
return (
<View style={styles.container} >
<Button onPress={this. openDB}
title="open Database"
color="#841584"/>
<Button onPress={this. populateDB}
title="Get Data"
color="#841584"/>
</View>
);
}
}
答案 1 :(得分:0)
所以我认为这可能只是时间问题。获取数据库对象的最安全方法是在成功回调中,如果在openDatabase中一切顺利,它将接收有效的db对象。所以将你的代码更改为此并尝试...
openCB(myDB) {
console.log("Database OPENED");
db = myDB;
};
openDB() {
SQLite.openDatabase({name : "sqliteexample", createFromLocation : 1}, this.openCB, this.errorCB);
}