如何在postgresql中为db创建用户?

187 php database authentication postgresql connection

我在我的CentOS服务器上安装了PostgreSQL 8.4,并从shell连接到root用户并访问PostgreSQL shell.

我在PostgreSQL中创建了数据库和用户.

尝试从我的PHP脚本连接时,它显示我的身份验证失败.

如何创建新用户以及如何为特定数据库授予权限?

Vid*_*dul 313

来自CLI:

$ su - postgres 
$ psql template1
template1=# CREATE USER tester WITH PASSWORD 'test_password';
template1=# GRANT ALL PRIVILEGES ON DATABASE "test_database" to tester;
template1=# \q
Run Code Online (Sandbox Code Playgroud)

PHP(在localhost上测试,它按预期工作):

  $connString = 'port=5432 dbname=test_database user=tester password=test_password';
  $connHandler = pg_connect($connString);
  echo 'Connected to '.pg_dbname($connHandler);
Run Code Online (Sandbox Code Playgroud)

  • 对于Ubuntu,它应该是:sudo -u postgres psql (54认同)
  • 请记住,您在shell中键入和运行的所有内容通常都会在shell历史记录中结束,包括您选择的密码. (30认同)
  • 对于Ubuntu,应该是`sudo su - postgres` (12认同)
  • 注意命令中```和```之间的区别! (7认同)
  • 我认为发布命令最便携的方式是:`psql -U postgres -c"CREATE ROLE ..."` (2认同)

Den*_*ret 40

使用密码创建用户:

http://www.postgresql.org/docs/current/static/sql-createuser.html

CREATE USER name [ [ WITH ] option [ ... ] ]

where option can be:

      SUPERUSER | NOSUPERUSER
    | CREATEDB | NOCREATEDB
    | CREATEROLE | NOCREATEROLE
    | CREATEUSER | NOCREATEUSER
    | INHERIT | NOINHERIT
    | LOGIN | NOLOGIN
    | REPLICATION | NOREPLICATION
    | CONNECTION LIMIT connlimit
    | [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'
    | VALID UNTIL 'timestamp'
    | IN ROLE role_name [, ...]
    | IN GROUP role_name [, ...]
    | ROLE role_name [, ...]
    | ADMIN role_name [, ...]
    | USER role_name [, ...]
    | SYSID uid
Run Code Online (Sandbox Code Playgroud)

然后授予特定数据库的用户权限:

http://www.postgresql.org/docs/current/static/sql-grant.html

示例:

grant all privileges on database db_name to someuser;
Run Code Online (Sandbox Code Playgroud)