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

2020-06-17 05:29:48易采站长站整理

首先是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_modulests-nodedistbin.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的差异