3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

コードとコメントだけのtypeorm入門

Last updated at Posted at 2019-07-29

コードだけしかないtypeorm入門

/*
//TypeScriptの基本以外で必要なパッケージ
sqlite3
typeorm

//tsconfig.jsonに必要な追加設定
{
  "compilerOptions": {
    "experimentalDecorators":true,
    "emitDecoratorMetadata":true
  }
}
*/
import * as typeorm from "typeorm";

/**
 *データ構造の定義
 *
 * @export
 * @class TestModel01
 */
@typeorm.Entity()
export class TestModel01 {
  @typeorm.PrimaryGeneratedColumn() //自動番号
  id!: number;

  @typeorm.Column() //一般データ
  name?: string;

  @typeorm.Column({
    default: () => "CURRENT_TIMESTAMP"
  }) //default値の指定:()=>"命令" でCURRENT_TIMESTAMPが文字列にならないように設定
  date!: Date;
}

/**
 *非同期主処理
 *
 */
async function Main() {
  //DBへ接続
  const con = await typeorm.createConnection({
    type: "sqlite",
    database: `test.sqlite`,
    entities: [TestModel01],
    logging: true
  });
  //DBの構造を初期化
  await con.synchronize();
  //テーブルアクセス用インスタンスの取得
  const testModel01 = con.getRepository(TestModel01);
  //テーブルへ挿入
  await testModel01.insert({ name: "あいうえお" });
  await testModel01.insert({ name: "かきくけこ" });
  //データの取得と表示
  const testValue01 = await testModel01.find();
  console.log("[出力結果]\n%s",JSON.stringify(testValue01,null , "  "));
  await con.close();
}

//主処理の呼び出し
Main();

/*
[出力結果]
[
  {
    "id": 1,
    "name": "あいうえお",
    "date": "2019-07-29T01:09:03.000Z"
  },
  {
    "id": 2,
    "name": "かきくけこ",
    "date": "2019-07-29T01:09:03.000Z"
  }
]
*/
3
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?