探索React Native开发的利器:react-native-sqlite-2
import SQLite from "react-native-sqlite-2";
// 创建或打开数据库
const dbPath = SQLite.openDatabase({ name: "myDatabase.db" });
// 创建表
dbPath.transaction((tx) => {
tx.executeSql(
'CREATE TABLE IF NOT EXISTS People (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)',
[],
() => console.log("Table created"),
(error) => console.error("Error creating table: ", error)
);
});
// 插入数据
dbPath.transaction((tx) => {
tx.executeSql(
'INSERT INTO People (name, age) VALUES (?, ?)',
['Alice', 30],
() => console.log("Row inserted"),
(error) => console.error("Error inserting row: ", error)
);
});
// 查询数据
dbPath.transaction((tx) => {
tx.executeSql(
'SELECT * FROM People',
[],
(_, { rows: { _array } }) => console.log("Rows selected: ", _array),
(error) => console.error("Error selecting row: ", error)
);
});
// 更新数据
dbPath.transaction((tx) => {
tx.executeSql(
'UPDATE People SET age = ? WHERE name = ?',
[31, 'Alice'],
() => console.log("Row updated"),
(error) => console.error("Error updating row: ", error)
);
});
// 删除数据
dbPath.transaction((tx) => {
tx.executeSql(
'DELETE FROM People WHERE name = ?',
['Alice'],
() => console.log("Row deleted"),
(error) => console.error("Error deleting row: ", error)
);
});
这段代码展示了如何在React Native项目中使用react-native-sqlite-2
库来进行SQLite数据库的基本操作,包括创建表、插入数据、查询数据、更新数据和删除数据。这对于需要在移动应用中集成数据库功能的开发者来说是一个很好的学习资源。
评论已关闭