0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rustでsqlx(PostgreSQL)を使う

Last updated at Posted at 2025-01-28

PostgreSQL側のコマンド

データベースの操作

ターミナルにて、

  • デフォルトのデータベースに接続
$ psql -d postgres
  • データベースの一覧を表示
$ \l
または
$ SELECT * FROM pg_database;

ここで、postgres,template0,template1と名付けられたデータベースは初期からあるデータベースで、postgresがデフォルトになっている

  • データベースの作成
$ CREATE DATABASE {データベース名};

ただし、データベース名に大文字を付けたい場合は、データベース名を"二重引用符”でくくる

  • データベースの削除
$ DROP DATABASE {データベース名};
  • データベースの選択
\c {データベース名}

sqlxコマンド

  • 終了する
$ postgres=# \quit

環境設定

sqlx-cliをインストールする
今回はPostgreSQLを使います。

cargo install sqlx-cli --no-default-features --features native-tls,postgres

データベースを作成する

sqlx database create

マイグレートする
例としてusersをマイグレートする

sqlx migrate add -r users

migrationsに2つのファイルが生成される

  • downにはDropに関するsql
  • upにはテーブルを作成するsql

をそれぞれ記述する

マイグレーションを実行する

sqlx migrate run
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?