Skip to content

Instantly share code, notes, and snippets.

@MarshalW
Last active March 17, 2022 03:52
Show Gist options
  • Save MarshalW/03d6969fd8a1f14aacc7d5d730052400 to your computer and use it in GitHub Desktop.
Save MarshalW/03d6969fd8a1f14aacc7d5d730052400 to your computer and use it in GitHub Desktop.
typeorm 使用 javascript 最简单代码

typeorm 使用 javascript 最简单代码

准备:

mkdir typeorm-demo && cd typeorm-demo
npm init -y
npm i typeorm sqlite3

user实体代码(users.js):

const EntitySchema = require("typeorm").EntitySchema;

module.exports = new EntitySchema({
  name: "User",
  tableName: "users",
  columns: {
    id: {
      primary: true,
      type: "int",
      generated: true,
    },
    name: {
      type: "varchar",
    },
  },
});

主程序 app.js

const typeorm = require("typeorm");

typeorm
  .createConnection({
    type: "sqlite",
    database: "./db.sqlite",
    synchronize: true,
    entities: [require("./users")],
  })
  .then(function (connection) {
    const user = {
      name: "zhangsan",
    };
    const userRepository = connection.getRepository("User");
    userRepository.save(user);
  })
  .catch(function (error) {
    console.log(error);
  });

执行并检查是否生效:

node app.js

sqlite3 db.sqlite
SQLite version 3.37.0 2021-12-09 01:34:53
Enter ".help" for usage hints.
sqlite> .schema
CREATE TABLE IF NOT EXISTS "users" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar NOT NULL);
CREATE TABLE sqlite_sequence(name,seq);
sqlite> select * from users;
1|zhangsan
sqlite> ^D
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment