我正在尝试使用 expo-sqlite 在我的 React Native 应用程序中创建和初始化数据库,使用 Expo 作为处理程序在本机 iOS 设备上使用 Expo Go 测试应用程序以供参考。
openDatabase()
是日落,有利于 openDatabaseAsync()
。我无法初始化数据库。我收到非标准 C++ 异常、RCTFatal、RCTConvertArrayValue 错误。有时我可以让它工作,但数据库无法初始化。
// Nutrition Database stored here.
// Done with documentation from sq-lite as certain functions have been sunset.
import * as SQLite from 'expo-sqlite';
const nutriDB = await SQLite.openDatabaseAsync('nutritionDB.db');
// Set up the table, only will create if it doesn't exist.
const initializeDatabase = async () => {
try {
await nutriDB.execAsync(`PRAGMA journal_mode = WAL;
CREATE TABLE IF NOT EXISTS NutritionInput (
NutritionInputID INTEGER PRIMARY KEY AUTOINCREMENT,
Date TEXT,
FoodEntries TEXT,
MealType TEXT CHECK (MealType IN ('Breakfast', 'Lunch', 'Dinner', 'Snack')),
TransFat REAL CHECK(TransFat >=0),
SatFat REAL CHECK (SatFat >= 0),
TotalCalories REAL CHECK (TotalCalories >=0)
);
`);
console.log('Nutrition table initialized successfully!');
}
catch (error) {
console.error('Error creating the table: ', error);
}
}
export default { nutriDB, initializeDatabase }
像 WatermelonDB 这样的解决方案需要放弃 Expo 构建。我想要一个与 Expo 和 Expo Go 应用程序配合使用的解决方案。
我刚刚遇到这个问题。首先我检查了 SQLite.openDatabaseSync 是否有效,它确实有效,这意味着这是一个异步问题。
然后,我将所有异步代码放入一个函数中,包括连接到数据库 (SQLite.openDatabaseAsync),然后从 useEffect 调用它们,这样就不会太早调用它们。
就您而言,类似以下内容对我有用:
`import React, { useEffect } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import * as SQLite from 'expo-sqlite';
const initializeDatabase = async () => {
try {
const nutriDB = await SQLite.openDatabaseAsync('nutritionDB.db');
await nutriDB.execAsync(`PRAGMA journal_mode = WAL;
CREATE TABLE IF NOT EXISTS NutritionInput (
NutritionInputID INTEGER PRIMARY KEY AUTOINCREMENT,
Date TEXT,
FoodEntries TEXT,
MealType TEXT CHECK (MealType IN ('Breakfast', 'Lunch', 'Dinner', 'Snack')),
TransFat REAL CHECK(TransFat >=0),
SatFat REAL CHECK (SatFat >= 0),
TotalCalories REAL CHECK (TotalCalories >=0)
);
`);
console.log('Nutrition table initialized successfully!');
}
catch (error) {
console.error('Error creating the table: ', error);
}
}
export default function App() {
useEffect(() => {
// Call the async function inside useEffect
initializeDatabase();
}, []);
return (
<View style={styles.container}>
<Text style={styles.text}>SQLite Async Example</Text>
<Text>Check the console for database output.</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
text: {
fontSize: 24,
fontWeight: 'bold',
},
});
`: