Ubuntu14.04安装PostpreSQL9.3.5记录

时间:2023-03-09 04:57:03
Ubuntu14.04安装PostpreSQL9.3.5记录

安装参考:http://www.postgresql.org/download/linux/ubuntu/

y@y:~$ sudo apt-get install postgresql-9.3  postgresql-client-9.3  postgresql-contrib-9.3 postgresql-server-dev-9.3  pgadmin3 

* Starting PostgreSQL 9.3 database server [ OK ]
正在设置 postgresql-contrib-9.3 (9.3.5-0ubuntu0.14.04.1) ...
Processing triggers for libc-bin (2.19-0ubuntu6) ...

表示安装成功。

配置:

1:使用psql客户端登录

y@y:~$ sudo -u postgres psql
psql (9.3.)
Type "help" for help.

2:修改PostgreSQL默认用户postgres的登录密码

PostgreSQL数据默认会创建一个postgres的数据库用户作为数据库的管理员,密码是随机的,所以这里要修改密码。

postgres=# alter user postgres with password 'postgres';
ALTER ROLE

3:退出PostgreSQL psql客户端

postgres-# \q
could not save history to file "/var/lib/postgresql/.psql_history": 没有那个文件或目录
(重新登录就可以了,由于第一次文件是不存在的)

4:修改linux系统的postgres用户的密码

y@y:~$ sudo passwd -d postgres
passwd:密码过期信息已更改。
y@y:~$ sudo -u postgres passwd
输入新的 UNIX 密码:
重新输入新的 UNIX 密码:
passwd:已成功更新密码

5:修改PostgresSQL数据库配置实现远程访问

y@y:~$ sudo vim /etc/postgresql/9.3/main/postgresql.conf
().监听任何地址访问,修改连接权限
#listen_addresses = ‘localhost’改为 listen_addresses = ‘*’
().启用密码验证
#password_encryption = on改为password_encryption = on
().可访问的用户ip段
y@y:/etc/postgresql/9.3/main$ sudo vim pg_hba.conf
并在文档末尾加上以下内容
# to allow your client visiting postgresql server
host all all 0.0.0.0 0.0.0.0 md5
():重启PostgreSQL数据库
y@y:~$ /etc/init.d/postgresql restart
* Restarting PostgreSQL 9.3 database server * Error: You must run this program as the cluster owner (postgres) or root
[fail]
重启失败,提示需要root权限
y@y:~$ sudo /etc/init.d/postgresql restart
* Restarting PostgreSQL 9.3 database server [ OK ]
y@y:~$

6:管理PostgreSQL用户和数据库

()登录postgre SQL数据库
y@y:~$ sudo psql -U postgres -h 127.0.0.1
Password for user postgres:
()创建新用户test,但不给建数据库的权限
用户名要用双引号,以区分大小写,密码不用
postgres=# create user "test" password 'test' nocreatedb;
CREATE ROLE
()建立数据库,并指定所有者
postgres=# create database "testdb" with owner="test";
CREATE DATABASE ()在外部命令行的管理命令
postgres=# -u postgres createuser -D -P test1
-D该用户没有创建数据库的权利,-P提示输入密码,选择管理类型y/n
postgres-# -u postgres createdb -O test1 db1
-O设定所有者为test1
登录数据库
y@y:~$ psql -U test -d testdb -h 127.0.0.1 -p
Password for user test:
psql (9.3.)
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: )
Type "help" for help. testdb=>

7:基本的数据库操作,就是使用一般的SQL语言

# 创建新表
CREATE TABLE user_tbl(name VARCHAR(20), signup_date DATE);
# 插入数据
INSERT INTO user_tbl(name, signup_date) VALUES('张三', '2013-12-22');
# 选择记录
SELECT * FROM user_tbl;
# 更新数据
UPDATE user_tbl set name = '李四' WHERE name = '张三';
# 删除记录
DELETE FROM user_tbl WHERE name = '李四' ;
# 添加栏位
ALTER TABLE user_tbl ADD email VARCHAR(40);
# 更新结构
ALTER TABLE user_tbl ALTER COLUMN signup_date SET NOT NULL;
# 更名栏位
ALTER TABLE user_tbl RENAME COLUMN signup_date TO signup;
# 删除栏位
ALTER TABLE user_tbl DROP COLUMN email;
# 表格更名
ALTER TABLE user_tbl RENAME TO backup_tbl;
# 删除表格
DROP TABLE IF EXISTS backup_tbl;