typescript连接mysql_Nest恶补Typeorm - Typeorm快速入门学习(结合typescript)

Typeorm快速入门学习

简单粗暴,主要和mongoose差不多的使用功能,快速学习

官方githubAPI(点击跳转) 官方API(点击跳转)

1.安装(和官方一样使用mysql,其它数据库请安装其它的依赖包)

npm install typeorm reflect-metadata @types/node mysql --save

2.TypeScript编译器版本3.3或更高版本,并且您已启用以下设置tsconfig.json

“ emitDecoratorMetadata ”: true,

“ experimentalDecorators ”: true,

3.连接到mysql数据库(单个数据库连接)

import {createConnection} from "typeorm";

try{

const connection = await createConnection({

type: "mysql", // 数据库类型

host: "localhost", // host,本地localhost/127.0.0.1

port: 3306, // 数据库端口号,mysql默认3306

username: "test", // 登录数据库的账号

password: "test", // 登录数据库的密码

database: "test", // mysql中的test数据库

entities: [__dirname + "/entity/*{.js,.ts}"], //表示扫描到的实例类的位置,src下面的/entity文件夹下面的任意.ts或.js文件

synchronize: true // 是否同步

});

}catch(error){//连接出错

console.log(error);

}

3.1在项目根目录(和package.json同级的地方)创建ormconfig.json。抽离出上面的连接对象放到该文件中

{

"type": "mysql",

"host": "localhost",

"port": 3306,

"username": "test",

"password": "test",

"database": "test",

"entities": ["src/entity/*{.js,.ts}"],

"synchronize": true

}

然后连接就不需要传递对象了,typeORM会在根目录下查找ormconfig.json文件,并连接

import {createConnection} from "typeorm";

try{

const connection = await createConnection();

}catch(error){//连接出错

console.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值