PostgreSQL Introduction
PostgreSQL is a powerful open source object-relational database management system (ORDBMS). For securely storing data; support best practices, and allows them to retrieve in processing the request.
PostgreSQL (also known as Post-gress-Q-L
) developed by the PostgreSQL Global Development Group (global volunteer team). It is not subject to any company or other private entities control. It is open source, the source code is freely available.
PostgreSQL is cross-platform, can run on many operating systems, such as Linux, FreeBSD, OS X, Solaris and Microsoft Windows and so on.
PostgreSQL's official website is: https://www.postgresql.org/
PostgreSQL features
PostgreSQL's features are as follows -
- PostgreSQL runs on all major operating systems (ie Linux, UNIX (AIX, BSD, HP-UX, SGI IRIX, Mac OS X, Solaris, Tru64), and Windows, etc.).
- PostgreSQL supports text, images, sound and video, and includes programming interfaces for C / C ++, Java, Perl, Python, Ruby, Tcl, and Open Database Connectivity (ODBC) is.
- PostgreSQL supports many features of SQL, such as complex SQL queries, SQL sub-select, foreign keys, triggers, views, business, multi-process concurrency control (MVCC), streaming replication (9.0), hot spare (9.0)).
- In PostgreSQL, a table can be set from the "parent" table inheritance further.
- A plurality of extensions may be installed to add additional functionality to the PostgreSQL.
PostgreSQL Tools
There are some open source and paid tools can be used as front-end tool for PostgreSQL. Here are a few tools are widely used:
1. psql:
It is a command-line tool, but also the main tool for PostgreSQL administration. pgAdmin
PostgreSQL is free and open source graphical user interface management tool.
2. phpPgAdmin:
It is a Web-based management tool written in PHP PostgreSQL. It is based MySQL administration tool phpMyAdmin functions to develop. It can be used as the tool for PostgreSQL.
3. pgFouine:
It is a log analyzer, you can create reports from a PostgreSQL log file. There are proprietary tools -
Lightning Admin for PostgreSQL, Borland Kylix, DBOne, the DBTools Manager PgManager, Rekall, the Data Architect, SyBase Power Designer, in the Microsoft Access, ERWIN, DeZign for Databases, PGExplorer, Studio Case 2, pgEdit, RazorSQL, MicroOLAP Database Designer , Aqua Data Studio, Tuples, EMS Database Management Tools for PostgreSQL, Navicat, SQL Maestro Group products for PostgreSQL, Datanamic DataDiff for PostgreSQL, Datanamic SchemaDiff for PostgreSQL, DB MultiRun PostgreSQL Edition, SQLPro, SQL Image Viewer, SQL Data Sets and so on.
PostgreSQL installation (Linux)
First, install the PostgreSQL client.
sudo apt-get install postgresql-client
Then, install PostgreSQL server.
sudo apt-get install postgresql
Under normal circumstances, after the installation is complete, PostgreSQL server automatically turned on 5432 port of the machine.
If you want to install a graphical management interface, you can run the following command, but the article does not cover this aspect.
sudo apt-get install pgadmin3
Adding new users and new databases
After the initial installation, the default name to generate a postgres database and the user database is called postgres. It should be noted that also generated a Linux system user named postgres's.
Here, we use postgres user, and other users to generate a new database. Several ways to achieve this goal, describes two here.
The first method, using PostgreSQL console.
First, create a new Linux user, you can get the name you want, here dbuser.
sudo adduser dbuser
then switch to postgres user.
sudo su - postgres
Next, log in using the PostgreSQL psql console command.
psql
effectively as postgres system user database with the same name as a user, log database, which is not to enter a password. If all goes well, the system prompt will change to "postgres = #", represents this time has entered the database console. The following commands are completed within the console.
The first thing is to use the password command to set a password for the user postgres.
password postgres
second thing is to create a database user dbuser (just created a Linux system users), and set a password.
CREATE USER dbuser WITH PASSWORD '; password ' ;;
third thing is to create a user database, here exampledb, and specify an owner for dbuser.
CREATE DATABASE exampledb OWNER dbuser;
The fourth thing is that all authority is given dbuser exampledb database, otherwise dbuser can only log into the console, the database does not have any operating authority.
GRANT ALL PRIVILEGES ON DATABASE exampledb to dbuser ;
Finally, q command to exit the console (can also press ctrl + D).
q
The second method, using the shell command line.
Adding new users and new databases, in addition to PostgreSQL console, you can also complete at the shell command line. This is because PostgreSQL provides a command-line program createuser and createdb. Or to create a new user and database exampledb dbuser example.
First, create a database user dbuser, and designated it as the root user.
sudo -u postgres createuser --superuser dbuser
Then, log database console, set dbuser user's password, exit the console when finished.
sudo -u postgres psql
password dbuser
q
Then, in the shell command line, create a database exampledb, and specify an owner for dbuser.
sudo -u postgres createdb -O dbuser exampledb
Log database
After adding new users and new databases, it is necessary in the name of the new user login database, then use the psql command.
psql -U dbuser -d exampledb -h 127.0.0.1 -p 5432
above command meaning of the parameters is as follows: -U specified user, -d specified database, -h specified server, -p designated port.
Enter the above command in the future, the system will prompt dbuser user's password. Enter the correct, you can log the console.
psql command presence shorthand. If the current user Linux system, but also the PostgreSQL user can omit the user name (parameter portion -U). For example, my Linux system user name ruanyf, and there PostgreSQL database user of the same name, then after I log on to ruanyf Linux system, you can log into the database using the following commands directly, and does not require a password.
psql exampledb
At this time, if there is internal PostgreSQL database with the current user of the same system, even if the database name can be omitted. For example, suppose there called ruanyf database, you simply type psql can log on to the database.
psql
Further, if the external data to be restored, the following command can be used.
psql exampledb < exampledb.sql
Console Commands
In addition to the password command (password) has already been used and the command q (quit), the console also offers a range of other commands.
h: View explain SQL commands, such as h select.
?: View psql command list.
l: List all databases.
c [database_name]: connect to other databases.
d: Lists all tables of the current database.
d [table_name]: List of a structure of a table.
du: List all users.
e: Opening a text editor.
conninfo: Lists the current database and connections.
PostgreSQL installation (Windows)
PostgreSQL installed on your Windows system, follow these steps. Close third-party anti-virus software during installation.
Select PostgreSQL version number and the corresponding system you want, and download and download from here: http://www.enterprisedb.com/products-services-training/pgdownload#windows
Since my system is Windows 10 64 bits, so choose the corresponding version -
- PostgreSQL9.6.2
- Windows x86-64
Run as administrator downloaded Postgresql-9.6.2-windows.exe
to install PostgreSQL. And install other software, there is nothing special, choose the installation directory, etc. Next just fine.
Select the location you want to install. By default, it is installed in the program folder ( C:\Program File
) in.
Select a directory to store data. By default, it is stored in PostgreSQL installation directory data
under the directory where the default on the line -
You will be asked to set a password, so please enter a password, enter the password I was here: 123456
.
PostgreSQL server port settings, keep the default, click Next -
This step will be asked to select the "locale", keep the default here. Then start the installation -
The installation process is ready. It takes some time to complete the installation process. After completing the installation process, you will see the following screen -
Cancel the check box button, and then click the complete button to complete the installation.
Create a database
In PostgreSQL, you can use the CREATE DATABASE
command to create the database.
grammar:
1
|
CREATE
DATABASE
database_name;
|
Here database_name
is the name of the database to be created.
PostgreSQL database is created using the UI
在您的系统中安装PostgreSQL后,打开开始菜单,然后单击pgAdmin。会得到一个这样的页面:
打开pgAdmin,第一次打开可能需要你输入密码,结果如下 -
右键单击PostgreSQL 9.6
并将PostgreSQL连接到本地主机服务器。
右键单击数据库(Databases),转到新数据库,将出现一个弹出框,如下图所示 -
然后键入您要的数据库名称,这里创建的数据库名称是:yiibai_db,如下图所示 -
点击保存(Save)就可以了。
创建新的数据库(yiibai_db)如下图所示 -
PostgreSQL使用查询工具创建数据库
打开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 | 它指定true 或false 的状态。 |
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/