我使用的是Android模拟器,所以我把users.db放在了"Android/app/src/main/assets/users.db"中。我已经运行了npx react-native link
来创建链接。我使用的是React Native 6.0以上版本,带有自动链接。
我得到了";错误:无法打开数据库":
import React, {Component} from 'react'
import {View, Text, Alert} from 'react-native'
import SQLite from 'react-native-sqlite-storage'
export default class App extends Component {
constructor(props) {
super(props)
SQLite.openDatabase({name:'users', createFromLocation:1}, this.connected, this.failed)
}
connected= () =>{
Alert.alert('Connected with success !')
}
failed= (e) =>{
Alert.alert('Something went wrong !', `${e}`)
}
render(){
return(
<View>
<Text>Testing SQLite</Text>
</View>
)
}
}
将属性createFromLocation
更改为数字2时,系统会创建自己的空数据库,因此需要创建表。不幸的是,我没能使用我的旧数据库。
您需要将数据库放入assets/www
文件夹中才能使其工作。
只有在我从设备上完全卸载应用程序并使用npx react-native run-android
从头开始重新安装后,才读取预填充的数据库。
当应用程序已经在设备上时,仅仅重新加载它是不够的。
我从react-native.config.js中删除了它,它起到了的作用
"react-native-sqlite-storage": {
platforms: {
android: {
sourceDir:
"../node_modules/react-native-sqlite-storage/platforms/android-native",
packageImportPath: "import io.liteglue.SQLitePluginPackage;",
packageInstance: "new SQLitePluginPackage()"
}
}
}
参考:Github
数据库的完整文件路径应该是"\android\app\src\main\assets\www"。