当前位置:Gxlcms > 数据库问题 > PostgresSQL数据库安装及操作

PostgresSQL数据库安装及操作

时间:2021-07-01 10:21:17 帮助过:17人阅读

打开SQL Shell(psql),执行以下创建语句 -

create database testdb;

执行结果如下 -

技术图片

查看数据库 -

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 postgres=# \l                                                         数据库列表    名称    |  拥有者  | 字元编码 |            校对规则            |             Ctype              |       存取权限 -----------+----------+----------+--------------------------------+--------------------------------+-----------------------  postgres  | postgres | UTF8     | Chinese (Simplified)_China.936 | Chinese (Simplified)_China.936 |  template0 | postgres | UTF8     | Chinese (Simplified)_China.936 | Chinese (Simplified)_China.936 | =c/postgres          +            |          |          |                                |                                | postgres=CTc/postgres  template1 | postgres | UTF8     | Chinese (Simplified)_China.936 | Chinese (Simplified)_China.936 | =c/postgres          +            |          |          |                                |                                | postgres=CTc/postgres  testdb    | postgres | UTF8     | Chinese (Simplified)_China.936 | Chinese (Simplified)_China.936 |  yiibai_db | postgres | UTF8     | Chinese (Simplified)_China.936 | Chinese (Simplified)_China.936 | (5 行记录)     postgres=#

或者在 pgAdmin 的左侧中查看,结果如下 -

技术图片

 数据类型

数据类型指定要在表字段中存储哪种类型的数据。 在创建表时,对于每列必须使用数据类型。

PotgreSQL中主要有三种类型的数据类型。 此外,用户还可以使用CREATE TYPE SQL命令创建自己的自定义数据类型。

以下是PostgreSQL中主要有三种类型的数据类型:

  • 数值数据类型
  • 字符串数据类型
  • 日期/时间数据类型

数值数据类型

数字数据类型用于指定表中的数字数据。

名称描述存储大小范围
smallint 存储整数,小范围 2字节 -32768 至 +32767
integer 存储整数。使用这个类型可存储典型的整数 4字节 -2147483648 至 +2147483647
bigint 存储整数,大范围。 8字节 -9223372036854775808 至 9223372036854775807
decimal 用户指定的精度,精确 变量 小数点前最多为131072个数字; 小数点后最多为16383个数字。
numeric 用户指定的精度,精确 变量 小数点前最多为131072个数字; 小数点后最多为16383个数字。
real 可变精度,不精确 4字节 6位数字精度
double 可变精度,不精确 8字节 15位数字精度
serial 自动递增整数 4字节 1 至 2147483647
bigserial 大的自动递增整数 8字节 1 至 9223372036854775807

 

 

 

 

 

 

 

 

字符串数据类型

String数据类型用于表示字符串类型值。

数据类型描述
char(size) 这里size是要存储的字符数。固定长度字符串,右边的空格填充到相等大小的字符。
character(size) 这里size是要存储的字符数。 固定长度字符串。 右边的空格填充到相等大小的字符。
varchar(size) 这里size是要存储的字符数。 可变长度字符串。
character varying(size) 这里size是要存储的字符数。 可变长度字符串。
text 可变长度字符串。

 

 

 

 

 

 

 

日期/时间数据类型

日期/时间数据类型用于表示使用日期和时间值的列。

名称描述存储大小最小值最大值解析度
timestamp [ (p) ] [不带时区 ] 日期和时间(无时区) 8字节 4713 bc 294276 ad 1微秒/14位数
timestamp [ (p) ]带时区 包括日期和时间,带时区 8字节 4713 bc 294276 ad  
date 日期(没有时间) 4字节 4713 bc 5874897 ad 1微秒/14位数
time [ (p) ] [ 不带时区 ] 时间(无日期) 8字节 00:00:00 24:00:00 1微秒/14位数
time [ (p) ] 带时区 仅限时间,带时区 12字节 00:00:00+1459 24:00:00-1459 1微秒/14位数
interval [ fields ] [ (p) ] 时间间隔 12字节 -178000000年 178000000年 1微秒/14位数

 

 

 

 

 

 

 

 

 

 

一些其他数据类型

布尔类型:

名称描述存储大小
boolean 它指定truefalse的状态。 1字节

 

 

货币类型:

名称描述存储大小范围
money 货币金额 8字节 -92233720368547758.08 至 +92233720368547758.07

 

 

几何类型:

几何数据类型表示二维空间对象。最根本的类型: - 形成所有其他类型的基础。

名称存储大小表示描述
point 16字节 在一个平面上的点 (x,y)
line 32字节 无限线(未完全实现) ((x1,y1),(x2,y2))
lseg 32字节 有限线段 ((x1,y1),(x2,y2))
box 32字节 矩形框 ((x1,y1),(x2,y2))
path 16+16n字节 封闭路径(类似于多边形) ((x1,y1),…)
polygon 40+16n字节 多边形(类似于封闭路径) ((x1,y1),…)
circle 24字节 <(x,y),r>(中心点和半径)

 

 

 

 

 

 

 

 

数据库操作

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

技术图片
# 创建新表

CREATE TABLE usertbl(name VARCHAR(20), signupdate DATE);
# 插入数据

INSERT INTO usertbl(name, signupdate) 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 usertbl ALTER COLUMN signupdate SET NOT NULL;
# 更名栏位
ALTER TABLE usertbl RENAME COLUMN signupdate TO signup;
# 删除栏位
ALTER TABLE user_tbl DROP COLUMN email;
# 表格更名 
ALTER TABLE usertbl RENAME TO backuptbl;
# 删除表格
DROP TABLE IF EXISTS backup_tbl;
技术图片

Python连接PostgreSQL数据库

PostgreSQL可以使用psycopg2模块与Python集成。sycopg2是用于Python编程语言的PostgreSQL数据库适配器。 psycopg2是非常小,快速,稳定的。 

安装psycopg2:

pip install psycopg2

要使用psycopg2模块,必须首先创建一个表示数据库的Connection对象,然后可以选择创建可以帮助您执行所有SQL语句的游标对象。

连接到数据库

以下Python代码显示了如何连接到现有的数据库。 如果数据库不存在,那么它将自动创建,最后将返回一个数据库对象。

技术图片
#!/usr/bin/python

import psycopg2

conn = psycopg2.connect(database="testdb", user="postgres", password="pass123", host="127.0.0.1", port="5432")

print "Opened database successfully"
技术图片

在这里指定使用testdb作为数据库名称,如果数据库已成功打开连接,则会提供以下消息:

Open database successfully

创建表

以下Python程序将用于在先前创建的数据库(testdb)中创建一个表:

技术图片
#!/usr/bin/python

import psycopg2

conn = psycopg2.connect(database="testdb", user="postgres", password="pass123", host="127.0.0.1", port="5432")
print "Opened database successfully"

cur = conn.cursor()
cur.execute(‘‘‘CREATE TABLE COMPANY
       (ID INT PRIMARY KEY     NOT NULL,
       NAME           TEXT    NOT NULL,
       AGE            INT     NOT NULL,
       ADDRESS        CHAR(50),
       SALARY         REAL);‘‘‘)
print "Table created successfully"

conn.commit()
conn.close()
技术图片

当执行上述程序时,它将在数据库testdb中创建COMPANY表,并显示以下消息:

Opened database successfully
Table created successfully

 

插入操作

以下Python程序显示了如何在上述示例中创建的COMPANY表中创建记录:

技术图片
#!/usr/bin/python

import psycopg2

conn = psycopg2.connect(database="testdb", user="postgres", password="pass123", host="127.0.0.1", port="5432")
print "Opened database successfully"

cur = conn.cursor()

cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)       VALUES (1, ‘Paul‘, 32, ‘California‘, 20000.00 )");

cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)       VALUES (2, ‘Allen‘, 25, ‘Texas‘, 15000.00 )");

cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)       VALUES (3, ‘Teddy‘, 23, ‘Norway‘, 20000.00 )");

cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)       VALUES (4, ‘Mark‘, 25, ‘Rich-Mond ‘, 65000.00 )");

conn.commit()
print "Records created successfully";
conn.close()
技术图片

当执行上述程序时,它将在COMPANY表中创建/插入给定的记录,并显示以下两行:

1 2 Opened database successfully Records created successfully

SELECT操作

以下Python程序显示了如何从上述示例中创建的COMPANY表中获取和显示记录:

技术图片
#!/usr/bin/python

import psycopg2

conn = psycopg2.connect(database="testdb", user="postgres", password="pass123", host="127.0.0.1", port="5432")
print "Opened database successfully"

cur = conn.cursor()

cur.execute("SELECT id, name, address, salary  from COMPANY")
rows = cur.fetchall()
for row in rows:
   print "ID = ", row[0]
   print "NAME = ", row[1]
   print "ADDRESS = ", row[2]
   print "SALARY = ", row[3], "\n"

print "Operation done successfully";
conn.close()
技术图片

执行上述程序时,会产生以下结果:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Opened database successfully ID =  1 NAME =  Paul ADDRESS =  California SALARY =  20000.0   ID =  2 NAME =  Allen ADDRESS =  Texas SALARY =  15000.0   ID =  3 NAME =  Teddy ADDRESS =  Norway SALARY =  20000.0   ID =  4 NAME =  Mark ADDRESS =  Rich-Mond SALARY =  65000.0   Operation done successfully

更新操作

以下Python代码显示了如何使用UPDATE语句来更新任何记录,然后从COMPANY表中获取并显示更新的记录:

技术图片
#!/usr/bin/python

import psycopg2

conn = psycopg2.connect(database="testdb", user="postgres", password="pass123", host="127.0.0.1", port="5432")
print "Opened database successfully"

cur = conn.cursor()

cur.execute("UPDATE COMPANY set SALARY = 25000.00 where ID=1")
conn.commit
print "Total number of rows updated :", cur.rowcount

cur.execute("SELECT id, name, address, salary  from COMPANY")
rows = cur.fetchall()
for row in rows:
   print "ID = ", row[0]
   print "NAME = ", row[1]
   print "ADDRESS = ", row[2]
   print "SALARY = ", row[3], "\n"

print "Operation done successfully";
conn.close()
技术图片

执行上述程序时,会产生以下结果:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Opened database successfully Total number of rows updated : 1 ID =  1 NAME =  Paul ADDRESS =  California SALARY =  25000.0   ID =  2 NAME =  Allen ADDRESS =  Texas SALARY =  15000.0   ID =  3 NAME =  Teddy ADDRESS =  Norway SALARY =  20000.0   ID =  4 NAME =  Mark ADDRESS =  Rich-Mond SALARY =  65000.0   Operation done successfully

删除操作

以下Python代码显示了如何使用DELETE语句来删除记录,然后从COMPANY表中获取并显示剩余的记录:

技术图片
#!/usr/bin/python

import psycopg2

conn = psycopg2.connect(database="testdb", user="postgres", password="pass123", host="127.0.0.1", port="5432")
print "Opened database successfully"

cur = conn.cursor()

cur.execute("DELETE from COMPANY where ID=2;")
conn.commit
print "Total number of rows deleted :", cur.rowcount

cur.execute("SELECT id, name, address, salary  from COMPANY")
rows = cur.fetchall()
for row in rows:
   print "ID = ", row[0]
   print "NAME = ", row[1]
   print "ADDRESS = ", row[2]
   print "SALARY = ", row[3], "\n"

print "Operation done successfully";
conn.close()
技术图片

执行上述程序时,会产生以下结果:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Opened database successfully Total number of rows deleted : 1 ID =  1 NAME =  Paul ADDRESS =  California SALARY =  20000.0   ID =  3 NAME =  Teddy ADDRESS =  Norway SALARY =  20000.0   ID =  4 NAME =  Mark ADDRESS =  Rich-Mond SALARY =  65000.0   Operation done successfully

本文参考https://www.yiibai.com/postgresql/

PostgresSQL数据库安装及操作

标签:文本编辑器   tcl   print   程序   mac os x   语句   多进程   contain   输入   

人气教程排行