1
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?

More than 5 years have passed since last update.

【insert/ update/ delete】データの挿入、更新、削除(複数データ挿入対応)[SQL/Rails]

Last updated at Posted at 2018-12-27

はじめに

開発するにあたって、手っ取り早く少数のデータをデータベースにインサートしたい時が多々ございました。
時と場合によりますが、有効な手段としてSQLを発行することがあります。
記憶することができず検索することが何度もあったので、削除、更新を含めて、ここに備忘録として簡単にまとめておきます。

SQL操作(基礎)

開発環境でデータベースにアクセスする

デフォルトでは開発環境で立ち上がります。今回のデータベースはMysqlだとします

$ rails db

今回はtextカラムとuser_idカラムデータを扱うとします。

データの挿入

mysql> insert into answers (text, user_id) values ('hello, takuyanin', 2);

データの更新

mysql> update answers set text = 'hello, world', user_id = 2 where id = 5;

データの削除

mysql> delete from answers where id = 5;

SQL操作(応用)

複数のデータの挿入

通常のinsert文のvalues以下に複数記述するだけで複数データを登録できます。

mysql> insert into answers (text, user_id) values ('hello, takuyanin', 2), ('hi', 4), ('wow', 7), ('good morning', 3);

おわりに

参考になった方は、いいね、お願いします(^^)

1
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
1
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?