昨天用pg初始化數據庫的時候遇到一些坑,這裏給大家分享下。
先來看下我最終成功的執行過程。
sql腳本:
--
-- 創建用戶test_user並設置password爲test_password
create user test_user with password 'test_password';
-- 創建database test_db設置owner爲test_user
create database test_db with owner test_user;
-- 切換到新創建的test_db數據庫
\c test_db test_user;
-- 在新創建的數據庫中創建表
create table my_table
(
id serial not null
constraint my_table_pkey
primary key,
name varchar(40) default ''::character varying not null
);
在postgresql中執行上面的腳本,執行如下:
root@0ffd52b8bcf4:/# psql -U postgres -W -f db.sql
Password:
CREATE ROLE
CREATE DATABASE
Password for user test_user:
You are now connected to database "test_db" as user "test_user".
CREATE TABLE
root@0ffd52b8bcf4:/#
第一次讓輸入的爲postgres的密碼(如果沒有設置可以直接回車),第二次讓輸入的爲test_user的密碼,輸入上邊設置的密碼test_password即可。
用新創建的用戶登錄數據庫:
root@0ffd52b8bcf4:/# psql -U test_user -d test_db
psql (11.2 (Debian 11.2-1.pgdg90+1))
Type "help" for help.
test_db=> \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
----------------+-------------+----------+------------+------------+-----------------------
postgres | postgres | UTF8 | en_US.utf8 | en_US.utf8 |
template0 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgres +
| | | | | postgres=CTc/postgres
test_db | test_user | UTF8 | en_US.utf8 | en_US.utf8 |
(4 rows)
test_db=> \dt
List of relations
Schema | Name | Type | Owner
--------+----------+-------+-----------
public | my_table | table | test_user
(1 row)
test_db=>
現在來說下問題。
最初我執行的時候是在IDEA中(用的datagrip鏈接的),按照上面的腳本執行可以正常通過,但是每次執行完表都是在postgres數據庫下,在test_db數據庫中沒有表。
原因分析:
在IDEA客戶端中執行,切換使用的數據庫的時候沒有讓輸入新建用戶的密碼,在這種非交互客戶端中沒有給出鏈接失敗提示,所以切換到新數據失敗後後面的create table仍然是在postgres下執行的,所以最終表在postgres下。
關於\c(\connect)這塊的信息大家可以參考PostgreSQL 9.6.0 手冊和32.1.1. 連接字符串。