postgresql常用命令

来源:互联网 发布:我的淘宝网首页登录 编辑:程序博客网 时间:2024/06/11 22:21

postgresql中常用的命令:
postgresql中默认的用户名和数据库是postgres。

1:连接数据库
使用指定用户名user连接
psql -U user
例子:
psql -U postgres

只用指定用户名user连接数据库dbname
psql -U user -d dbname
例子:
psql -U postgres -d xa

2:退出数据库连接
\q

3:列举数据库
\l

4:切换数据库
\c dbname

5:列举当前连接数据库中的表
\dt

6:查看表结构
\d tblname

7:查看索引
\di

8:创建数据库
create database dbname;

9:删除数据库
drop database dbname;

10:创建表
创建一个pinfo表,包括id(key),name
create table pinfo(
id int8 not null,
name varchar(20) not null default ”,
primary key(id)
);

11:删除表
drop table dbname;

12:重命名一个表
将pinfo表命名为playerinfo
alter table pinfo rename to playerinfo;

13:向表中添加字段
按照表中字段结构插入数据
insert into pinfo values (1, ‘kobe’);
向表中插入指定字段的数据
insert into pinfo (name, id) values (‘james’, 2);

14:搜索表中的数据
搜索表中的全部字段的数据
select * from pinfo;
搜索表中指定字段的数据
select id from pinfo;
搜索表中指定条件的数据
select * from pinfo where name=’kobe’;

15:删除表中的数据
删除表中全部的数据
delete from pinfo;
删除表中指定条件的数据
delete from pinfo where name=’james’;

16:向已有表中添加字段
alter table pinfo add column sex bool not null default false;

17:删除表中的字段
alter table pinfo drop column sex;

18:重命名表中字段
alter table pinfo rename column id to pid;

19:修改表中字段数据类型
alter table pinfo alter column pid type int2;

20:给表中字段设置缺省值
alter table pinfo alter column age set default 1;

21:删除表中字段的缺省值
alter table pinfo alter column age drop default;

22:更新表中的数据
更新表中某列的数据
update table pinfo set age=30;
更新表中满足某条件的某列的数据
update pinfo set age=30 where name=’kobe’;

23:when case的使用
select ( case vip when 14 then ‘a’ when 13 then ‘b’ else ‘c’ end) as vip from pinfo;

24:备份数据库
加-c在导入数据库时会清空原有的数据库,否则会有….exist报错
pg_dump -h localhost -U postgres -p 5432 -d xa -c -f “F:\database\xa_temp.dmp”

25:导入数据库
psql -h localhost -U postgres -d xa -f “F:\database\xa_temp.dmp”

26:导出数据库中某张表
pg_dump -h localhost -U postgres -p 5432 -d test -t pinfo > F:\database\pinfo.sql

27:查看系统用户信息
select usename from pg_user;

28:创建用户
create user testuser;

29:删除用户
drop user testuser;

30:查看版本信息
select version();

原创粉丝点击