使用NestJs TypeORM 连接SQL Server 教程相当少,查了好多资料都是Mysql或者MangoDB的。
搞了好多方法都不得要点
正确的方法,抄官网
//这个为database.provider.ts!!!
import { DataSource } from 'typeorm';
export const databaseProviders = [
{
provide: 'DATA_SOURCE',
useFactory: async () => {
const dataSource = new DataSource({
type: 'mssql',
host: 'localhost',
port: 1433,
username: 'sa',
password: 'xxx',
database: 'xxx',
entities: [
__dirname + '/../**/*.entity{.ts,.js}',
],
synchronize: true,
connectionTimeout: 15000,
requestTimeout: 15000,
pool:
{
max: 10,
min: 0,
idleTimeoutMillis: 30000
},
options: {
"encrypt": false // Windows Azure时设置为true,其他设置为false
},
extra: {
trustServerCertificate: true,
trustedConnection: true,
}
});
return dataSource.initialize();
},
},
];
database.module.ts
import { Module } from '@nestjs/common';
import { databaseProviders } from './database.providers';
@Module({
providers: [...databaseProviders],
exports: [...databaseProviders],
})
export class DatabaseModule {}
犯的错误如下:
端口号:1433。因为范例大多是Mysql,要么端口号忘了,要么type错了。
app.module的import 模块切记用
@Module({
imports: [PostsModule, UsersModule, DatabaseModule
// TypeOrmModule.forRoot()
],
controllers: [AppController],
providers: [AppService],
})
// TypeOrmModule.forRoot() 这个工具是网上找的,不知道怎么填花了好长时间,不管用。
// export const DatabaseConfig1 = {
// type: ‘mysql’,
// host: ‘127.0.0.1’,
// port: 3306,
// username: ‘root’,
// password: ‘123456’,
// database: ‘example’,
// entities: [__dirname + ‘//*.entity{.ts,.js}'],
// synchronize: false,
// migrations: ['database/migration//*.ts’],
// cli: {
// migrationsDir: ‘database/migration/default’,
// },
// }
TypeOrmModule.forRoot(DatabaseConfig1 ) 不管用
而如下方法是可以的。
TypeOrmModule.forRoot({
// type: 'mssql',
// host: 'localhost',
// port: 1433,
// username: 'sa',
// password: 'xxxx',
// database: 'xxx',
// entities: [],
// synchronize: true,
// connectionTimeout :15000,
// requestTimeout :15000,
// pool:
// {
// max:10,
// min: 0,
// idleTimeoutMillis: 30000
// },
// options: {
// "encrypt": false // Windows Azure时设置为true,其他设置为false
// },
// extra:{
// trustServerCertificate:true,
// trustedConnection: true,
// }})
真是奇怪