---
# System prepended metadata

title: '[Ruby On Rails]在rails專案中用命令列操作db'
tags: [Ruby On Rails]

---

# [Ruby On Rails]在rails專案中用命令列操作db

###### tags: `Ruby On Rails`

(此處使用ubuntu14.06)

開啟terminal,在專案資料夾路徑輸入rails db


```terminal
twkhjl@ubuntu:~/sites/blog$ rails db
Password: (輸入密碼)
psql (9.3.24, server 12.0)
WARNING: psql major version 9.3, server major version 12.
         Some psql features might not work.
Type "help" for help.
```

db_blog=# <---看到命令列出現這個表示已進入postgreSQL的命列列狀態.

db_blog是此例中的資料庫名稱

但此時會發現輸入sql query不起作用,因為我們尚未連線至資料庫.

連線至資料庫:
\c 資料庫名稱


```terminal

db_blog=# \c db_blog
psql (9.3.24, server 12.0)
WARNING: psql major version 9.3, server major version 12.
         Some psql features might not work.
You are now connected to database "db_blog" as user "postgres".
db_blog=# 

```

此時即可下sql query,

記得結尾要加上;

```terminal
db_blog=# select * from articles;
 id | title  | text  |         created_at         |         updated_at         
----+--------+-------+----------------------------+----------------------------
  7 | title1 | tex1  | 2019-11-10 13:15:54.517463 | 2019-11-10 13:15:54.517463
  8 | title2 | text2 | 2019-11-10 13:16:01.760133 | 2019-11-10 13:16:01.760133
(2 rows)

db_blog=#
```

想要退出,輸入\q即可

```terminal
db_blog=# \q
twkhjl@ubuntu:~/sites/blog$ 
```