我想在我的Expo React本机项目中使用SQLite。因此,我下载了SQLite的数据库浏览器,并在将数据库和表加载到项目中之前创建了数据库和表。
现在,我已经有预填充的数据库想要加载到我的项目中。我有几个问题,例如该数据库不存在...等。但是我通过拥有一个数据库模块来解决了这个问题:
// Database.js
import * as SQLite from 'expo-sqlite';
module.exports = SQLite.openDatabase('myDb.db');
然后将其导入“屏幕”文件夹中的“主页”中:
import Database from '../db/database';
function myFunction(){
console.log("Enter Function");
console.log(Database);
Database.transaction(function(txn) {
console.log("Enter Transaction");
txn.executeSql(
"INSERT INTO users (name, email, password) VALUES ('Lama', 'lama@gmail,com', 'lam123');",
); //end txn
}, function (error){
console.log(error);
},
function(){
console.log("Success");
});
}//end myFunction()
控制台日志:
Enter Function
WebSQLDatabase {
"_currentTask": null,
"_db": SQLiteDatabase {
"_closed": false,
"_name": "myDb.db",
},
"_running": false,
"_txnQueue": Queue {
"length": 0,
},
"exec": [Function anonymous],
"version": "1.0",
}
Enter Transaction
Error code 1: no such table: users
- node_modules/expo-sqlite/build/SQLite.js:36:15 in _deserializeResultSet
* [native code]:null in map
- node_modules/expo-sqlite/build/SQLite.js:16:40 in SQLiteDatabase#exec
- node_modules/promise/setimmediate/core.js:37:14 in tryCallOne
- node_modules/promise/setimmediate/core.js:123:25 in setImmediate$argument_0
- node_modules/react-native/Libraries/Core/Timers/JSTimers.js:146:14 in _callTimer
- node_modules/react-native/Libraries/Core/Timers/JSTimers.js:194:17 in _callImmediatesPass
- node_modules/react-native/Libraries/Core/Timers/JSTimers.js:458:30 in callImmediates
* [native code]:null in callImmediates
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:407:6 in __callImmediates
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:143:6 in __guard$argument_0
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:384:10 in __guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:142:17 in __guard$argument_0
* [native code]:null in flushedQueue
* [native code]:null in invokeCallbackAndReturnFlushedQueue
我真的不知道我在这里缺少什么,我尝试了代码来创建另一个数据库,该数据库可以工作并添加记录(尽管我找不到笔记本电脑中数据库的位置)。我还尝试过将数据库浏览器中的记录添加到myDb中,并且它可以正常工作:
我发现之前曾问过这个问题,但没有帮助的答案: SQLite Expo API, no such table in pre-populated file?
提前谢谢!
答案 0 :(得分:1)
我猜
SQLite.openDatabase('myDb.db');
正在打开位于应用文件系统中路径为 {${FileSystem.documentDirectory}SQLite/myDb.db
的myDb.db数据库。
因此,如果没有名称为“ myDB.db”的文件,sqlite将创建一个具有相同名称的新数据库,
这就是为什么您无法在新创建的数据库中查找表用户的原因。
因此,要确保填充的数据库位于正确的路径中,您需要使用FileSytem将其下载到您的应用中,
所以您可能需要做这样的事情:
FileSystem.downloadAsync(
Asset.fromModule(require(path)).uri,
`${FileSystem.documentDirectory}SQLite/myDb.db`
)
.then(function(){
var db = SQLite.openDatabase('db.db')
// do whatever else you need here
})
.catch(error =>{
console.error(error)
})