Administrator
发布于 2026-01-18 / 0 阅读
0
0

PostgreSQL 在 Windows 下不会自动创建同名角色

PostgreSQL 官方文档里写了这么一条:"安装时会自动创建一个和当前用户名一致的角色(密码为空)"。

As an explanation for why this works: PostgreSQL user names are separate from operating system user accounts. When you connect to a database, you can choose what PostgreSQL user name to connect as; if you don't, it will default to the same name as your current operating system account. As it happens, there will always be a PostgreSQL user account that has the same name as the operating system user that started the server, and it also happens that that user always has permission to create databases. Instead of logging in as that user you can also specify the -U option everywhere to select a PostgreSQL user name to connect as.

解释为什么这样有效:PostgreSQL 用户名与操作系统账户是分开的。连接数据库时可以选择以哪个用户名连接;如果不选,就默认为当前操作系统账户的同名用户。事实上,总会存在一个与启动服务器的操作系统用户同名的 PostgreSQL 账户,而且它总有创建数据库的权限。你既可以用这个用户登录,也可以在所有命令里用 -U 指定要连接的用户名。

不过这一点在 Windows 上不成立:PostgreSQL 不会默认创建与当前系统用户名一致的角色。Linux 和 Windows 的差异在于:

  • Linux:默认使用 Peer 认证。以 Linux 用户 alice 登录并直接输入 psql 时,PostgreSQL 会尝试以数据库角色 alice 登录;安装时通常会自动映射,或由管理员手动建好同名角色,整套逻辑很顺滑。
  • Windows:默认安装包(如 EDB 安装包)通常只创建一个超级用户角色 postgres,并要求设置密码,不会为当前 Windows 登录名(如 Administrator 或你的用户名)自动创建同名数据库角色。

而 createdb、dropdb、psql 这些命令在不指定用户名时,默认用的正是当前系统用户名。所以练手时可以显式加上 -U, --username=USERNAME:

createdb -U postgres

当然,也可以手动创建一个与当前系统用户名一致的角色,省去每次指定的麻烦(注意用单引号):

CREATE ROLE your_system_uname WITH LOGIN CREATEDB PASSWORD 'your_password'

评论