nodejs环境使用Typeorm连接查询Oracle数据

2022-01-14,,,,

这篇文章主要介绍了nodejs环境使用Typeorm连接查询Oracle数据,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下

首先是typeorm的官方地址,

国内有人翻了中文版,不保证时效性

・通过npm安装下列包:

  • typeorm //typeorm连接数据库
  • @types/node //类型系统
  • typescript //ts基础
  • oracledb //oracle基础
  • ts-node //nodejs编译运行ts的工具;

・根路径配置:

  • package.json //项目依赖、脚本、描述等
  • tsconfig.json //ts编译设置
 { "compilerOptions": { "module": "commonjs", "noImplicitAny": true, "removeComments": true, "preserveConstEnums": true, "sourceMap": true, "outDir": "./dist", "emitDecoratorMetadata": true,  //typeorm特需 "experimentalDecorators": true  //typeorm特需 }, "include": [ "src/**/*" ], "exclude": [ "node_modules", "**/*.spec.ts" ] }

ormconfig.json //数据库连接参数

 { "type": "oracle", "host": "10.16.2.41", "port": 1521, "username": "admin", "password": "admin", "sid": "ORCL", "synchronize": true, "logging": true, "entities": [ "src/entity/**/*.ts" ], "migrations": [ "src/migration/**/*.ts" ], "subscribers": [ "src/subscriber/**/*.ts" ] }

.vscode配置:launch.json ,主要配置vscode在debug时由ts编译所得的js路径,此项与项目勿关,只为了方便调试

 { "name": "Current TS File", "type": "node", "request": "launch", "program": "${workspaceRoot}\\node_modules\\ts-node\\dist\\bin.js", "args": [ "${relativeFile}" ], "cwd": "${workspaceRoot}", "protocol": "inspector" }

・编写主体:

根路径下创建/编辑index.ts(名字可自定义),配置package中start脚本命令为ts-node index.ts,

 import "reflect-metadata"; import {createConnection} from "typeorm"; import {xxx} from "./src/entity/xxx";  //引入数据表结构映射文件 createConnection().then(async connection => {  //连接参数为空时自动按照路径下ormconfig.json信息连接 /*let a = await connection.query( `SELECT * FROM xxx` ); *///直接使用原生sql语句查询 let a = await connection.manager.find(xxx)  //使用连接器查询 connection.manager console.log("result: ", a); }).catch(error => console.log(error));

 在src/entity/下构建数据表实体结构xxx.js,格式参考官网

 在cmd根路径运行npm start,或使用vscode调试

 至此,我们已经成功使用typeorm连接到了Oracle数据库,若要构成完整的后端只需添加中间件等等

・与sequelize的差异

从Sequelize转移到typeorm,是因为sequelize官方不支持连接Oracle

typeorm像名字中描述的那样,是个使用typescript编写的、类型系统非常完整的数据库关系映射,放张数据类型截图:

 这还是js吗?当然,如此完整的类型系统得益于typescript,我们也可以在构建时酌情使用类型声明,因为它不是必须的(本质仍是js)

 很多类型都可以使用js原生类型+长度代替,是否使用专用类型声明取决于实际需求

 根据数据库自动生成/更新映射文件脚本会相对复杂

 typescript也是初次接触,文章只是通过短短几星期的摸索得来,内容难免有误,若有错误还请点拨,谢谢

总结

如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

以上就是nodejs环境使用Typeorm连接查询Oracle数据的详细内容,更多请关注本站其它相关文章!

《nodejs环境使用Typeorm连接查询Oracle数据.doc》

下载本文的Word格式文档,以方便收藏与打印。