与数据库的打字稿连接

时间:2018-09-14 11:11:08

标签: typescript connection package tsc typeorm

我是TypeScript的新手,我想与数据库建立新连接并插入代码中提到的数据。我正确安装了软件包,我访问了typeorm.io网站,但无法正确安装typescript / tsc。 src / index.ts。

import "reflect-metadata";
import {createConnection} from "typeorm";
import {User} from "./entity/User";

createConnection({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "root",
    password: "welcome123@",
    database: "test",
    entities: [
        User
    ],
    synchronize: true,
    logging: false
}).then(async connection => {

    console.log("Inserting a new user into the database...");
    const user = new User();
    user.firstName = "Timber";
    user.lastName = "Saw";
    user.age = 25;
    await connection.manager.save(user);
    console.log("Saved a new user with id: " + user.id);

    console.log("Loading users from the database...");
    const users = await connection.manager.find(User);
    console.log("Loaded users: ", users);

    console.log("Here you can setup and run express/koa/any other 
   framework.");

}).catch(error => console.log(error));

这是文件,我定义了模型。 实体/User.ts

import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    firstName: string;

    @Column()
    lastName: string;

    @Column()
    age: number;

}

1 个答案:

答案 0 :(得分:0)

不要!!!!!! 该内容将转换为纯JS,并且所有服务器端信息都将公开(连接信息)。 尝试改为连接到API。 构建一个API并将其URI公开给您的客户端应用程序,并根据需要执行CRUD操作。