I’m trying to get a sqlite DB working in my react native (with expo) app, but I’m having troubles. I’ve created the DB command line in my assets/DB folder and created a table with 1 entry. I can query the DB in my IDE and I do find my entry so the table exists.
But when I launch my app, I get the error that no table was found. I had it working once, but while I didnt change the code.. it doesn’t work now.
App.tsx
const configDatabase = async () => {
const dbName = 'watchmeDB.db';
const dbAsset = require('./assets/DB/watchmeDB.db');
const dbUri = Asset.fromModule(dbAsset).uri;
const dbFilePath = `${FileSystem.documentDirectory}SQLite/${dbName}`;
try {
FileSystem.getInfoAsync(`${FileSystem.documentDirectory}SQLite/watchmeDB.db`)
.then(result => {
if (result.exists) {
const db = SQLite.openDatabaseAsync('watchmeDB.db');
} else {
FileSystem.downloadAsync(
Asset.fromModule(require('./assets/DB/watchmeDB.db')).uri,
`${FileSystem.documentDirectory}SQLite/watchmeDB.db`
).then(() => {
const db = SQLite.openDatabaseAsync('watchmeDB.db');
});
}
});
} catch (err) {
console.error(err);
}
};
...
useEffect(() => {
configDatabase()
.then(() => {
setDbLoaded(true);
})
.catch((error) => console.error(error));
}
,[])
...
return <SafeAreaProvider
initialMetrics={initialWindowMetrics}
onLayout={onLayoutRootView}
>
<StatusBar style="dark"/>
<Suspense fallback={fallback}>
<SQLite.SQLiteProvider assetSource={{ assetId: require('./assets/DB/watchmeDB.db') }} databaseName="watchmeDB.db" useSuspense>
<NavigationContainer theme={globalTheme}>
...
</NavigationContainer>
</SQLite.SQLiteProvider>
</Suspense>
</SafeAreaProvider>
HomeScreen.tsx
const db = useSQLiteContext();
useEffect(() => {
getData();
// db.withTransactionAsync(async () => {
// await getData();
// })
}, [db]);
async function getData() {
const result = await db.getAllAsync<Item>(`select * from watchme`);
console.log(result);
// setItems(result);
}
Do I also need to add something to make it read/write? So I can also use insert queries.
2
Here what you are missing is, creating a DB. you must create a new DB in all cases even if you are accessing an already created DB you need to initialize it like bellow:
useEffect(() => {
const ConntectToSql = async () => {
try {
const db = await SQLite.openDatabase({ name: 'watchmeDB', createFromLocation: '~www/watchmeDB.db' });
console.log(db)
} catch (error) {
alert(error.message)
console.log(error)
}
}
ConntectToSql()
}, []);
1