【发布时间】:2018-05-20 23:18:32
【问题描述】:
有人知道连接 react-native-sqlite-storage 的最佳方式吗?我的调试器在查询后得到“没有这样的表:nameOfTable(代码 1)”。
我应该从名为“person”的表中获取“id”、“name”和“last name”。 我已连接位于“/android/app/src/main/assets/mioDB.db”中的预填充数据库(“mioDB”)。
这是我的小代码:
import React,{Component} from 'react';
import {TextInput,View,Text,TouchableOpacity} from 'react-native';
import { openDatabase } from "react-native-sqlite-storage";
let mioDB = openDatabase('mioDB');
class App extends Component{
constructor(props){
super(props);
this.state={
name:'',
lastName:''
};
}
showData=()=>{
alert('name: '+this.state.name+' lastName: '+this.state.lastName);
};
listOfNames=()=>{
try{
mioDB.transaction((statement)=>{
console.log('****************');
statement.executeSql('SELECT * FROM person',[],(statement,results)=>{
console.log('****************');
var len = results.rows.length;
for (let i = 0; i < len; i++) {
let row = results.rows.item(i);
console.log(`Record: ${row.name}`);
}
});
});
}catch(error){
alert(error);
}
};
render(){
return(
<View style={{marginTop:100}}>
<TextInput style={{fontSize:20}} placeholder='name' onChangeText={(text)=>this.setState({name:text})}/>
<TextInput style={{fontSize:20}} placeholder='lastName' onChangeText={(text)=>this.setState({lastName:text})}/>
<TouchableOpacity style={{width:150,height:50}} onPress={this.showData}><Text>Create db</Text></TouchableOpacity>
<TouchableOpacity style={{width:150,height:50}} onPress={this.listOfNames}><Text>Show database</Text></TouchableOpacity>
</View>
);
}
}
export default App;
不知道哪里错了,因为系统很容易连接
【问题讨论】:
-
根据文档(github.com/andpor/…),预填充的文件应该在
www目录下,但您共享的路径不在www目录下。同样对于预填充的数据库,openDatabase需要一个对象。请进行这两项更改并尝试。 -
但是在同一个链接中我读到“对于 Android,www 目录总是相对于应用程序的资产目录:src/main/assets”,然后我替换了“www/mioDB.db “在资产文件夹中,它有效!谢谢你,Prasun
-
让我把它作为答案的一部分,这样任何寻找相同答案的人都可以快速找到解决方案。
标签: sqlite react-native react-native-android