如何在React Native中使用TypeORM编写SQLite连接代码
在React Native中使用TypeORM配置SQLite数据库连接
1. 安装必要依赖
首先安装TypeORM、React Native SQLite存储库以及元数据反射库:
npm install typeorm react-native-sqlite-storage reflect-metadata # 或用yarn yarn add typeorm react-native-sqlite-storage reflect-metadata
iOS项目需额外执行pod install完成原生依赖配置。
2. 替换PostgreSQL配置为SQLite配置
SQLite不需要主机、端口、用户名和密码这类配置,只需指定数据库文件路径即可。以下是修改后的完整配置:
新版本TypeORM(推荐用DataSource)
import { DataSource } from "typeorm"; import { Post, Category } from "./entities"; // 替换为你的实体文件路径 import RNFS from "react-native-fs"; const AppDataSource = new DataSource({ type: "sqlite", database: `${RNFS.DocumentDirectoryPath}/test.db`, // 数据库存放在应用文档目录 synchronize: true, // 开发环境可开启,自动同步实体到表结构,生产环境建议关闭 logging: true, entities: [Post, Category], subscribers: [], migrations: [], }); // 初始化连接 AppDataSource.initialize() .then(() => console.log("SQLite数据库连接成功")) .catch((err) => console.error("数据库连接失败:", err));
旧版本TypeORM(用createConnection)
import { createConnection } from "typeorm"; import { Post, Category } from "./entities"; import RNFS from "react-native-fs"; createConnection({ type: "sqlite", database: `${RNFS.DocumentDirectoryPath}/test.db`, synchronize: true, logging: true, entities: [Post, Category], subscribers: [], migrations: [], }) .then(() => console.log("SQLite连接成功")) .catch((err) => console.error("连接失败:", err));
关键配置说明
type: "sqlite":明确指定数据库类型为SQLitedatabase:设置数据库文件的存储路径,用react-native-fs获取应用文档目录可保证跨平台兼容性;若不想依赖该库,直接写文件名(如'test.db')也可,默认会存在应用沙盒内- 移除PostgreSQL配置里的
host、port、username、password字段,SQLite不需要这些参数 synchronize: true:开发阶段自动根据实体类创建或更新表结构,生产环境建议关闭,改用迁移脚本管理数据库变更
额外注意事项
- 确保你的实体类已正确使用TypeORM装饰器(比如
@Entity()、@Column()等) - 若遇到iOS或Android平台的配置问题,可检查
react-native-sqlite-storage的原生配置是否正确
内容的提问来源于stack exchange,提问作者qqqwerqqq
相关产品推荐
相关产品推荐

