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();