搞懂Python PostgreSQL的基本操作
C:\Users\Tutorialspoint>python -m pip install --upgrade pip
Collecting pip
Using cached
https://files.pythonhosted.org/packages/8d/07/f7d7ced2f97ca3098c16565efbe6b15fafcba53e8d9bdb431e09140514b0/pip-19.2.2-py2.py3-none-any.whl
Installing collected packages: pip
Found existing installation: pip 19.0.3
Uninstalling pip-19.0.3:
Successfully uninstalled pip-19.0.3
Successfully installed pip-19.2.2
C:\WINDOWS\system32>pip install psycopg2-binary
Collecting psycopg2-binary
Using cached
https://files.pythonhosted.org/packages/80/79/d0d13ce4c2f1addf4786f4a2ded802c2df66ddf3c1b1a982ed8d4cb9fc6d/psycopg2_binary-2.8.3-cp37-cp37m-win32.whl
Installing collected packages: psycopg2-binary
Successfully installed psycopg2-binary-2.8.3
import mysql.connector
D:\Python_PostgreSQL>import psycopg2
D:\Python_PostgreSQL>
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
import psycopg2
# 建立连接
conn = psycopg2.connect(
database="postgres", user='postgres', password='password',
host='127.0.0.1', port= '5432'
)
# 使用cursor()方法创建游标对象
cursor = conn.cursor()
# 使用execute()方法执行MYSQL函数
cursor.execute("select version()")
# 使用fetchone()方法获取单行。
data = cursor.fetchone()
print("Connection established to: ",data)
# 关闭连接
conn.close()
Connection established to: (
'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit',
)
Connection established to: (
'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit',
)
CREATE DATABASE dbname;
postgres=# CREATE DATABASE testdb;
CREATE DATABASE
# Filename : example.py # Copyright : 2020 By Lidihuo # Author by : www.lidihuo.com # Date : 2020-08-15 postgres=# \l List of databases Name | Owner | Encoding | Collate | Ctype | -----------+----------+----------+----------------------------+-------------+ mydb | postgres | UTF8 | English_United States.1252 | ........... | postgres | postgres | UTF8 | English_United States.1252 | ........... | template0 | postgres | UTF8 | English_United States.1252 | ........... | template1 | postgres | UTF8 | English_United States.1252 | ........... | testdb | postgres | UTF8 | English_United States.1252 | ........... | (5 rows)
C:\Program Files\PostgreSQL\11\bin> createdb -h localhost -p 5432 -U postgres sampledb
Password:
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
import psycopg2
# 建立连接
conn = psycopg2.connect(
database="postgres", user='postgres', password='password',
host='127.0.0.1', port= '5432'
)
conn.autocommit = True
# 使用cursor()方法创建游标对象
cursor = conn.cursor()
# 准备查询以创建数据库
sql = '''CREATE database mydb''';
# 创建数据库
cursor.execute(sql)
print("Database created successfully........")
# 关闭连接
conn.close()
Database created successfully........
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
);
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# CREATE TABLE CRICKETERS (
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age INT,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255));
CREATE TABLE
postgres=#
# Filename : example.py # Copyright : 2020 By Lidihuo # Author by : www.lidihuo.com # Date : 2020-08-15 postgres=# \dt List of relations Schema | Name | Type | Owner --------+------------+-------+---------- public | cricketers | table | postgres (1 row) postgres=#
# Filename : example.py # Copyright : 2020 By Lidihuo # Author by : www.lidihuo.com # Date : 2020-08-15postgres=# \d cricketers Table "public.cricketers" Column | Type | Collation | Nullable | Default ----------------+------------------------+-----------+----------+--------- first_name | character varying(255) | | | last_name | character varying(255) | | | age | integer | | | place_of_birth | character varying(255) | | | country | character varying(255) | | | postgres=#
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
import psycopg2
# 建立连接
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
# 使用cursor()方法创建游标对象
cursor = conn.cursor()
# 删除已存在的EMPLOYEE表
cursor.execute("DROP TABLE if EXISTS EMPLOYEE")
# 创建表
sql ='''CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) not NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT)'''
cursor.execute(sql)
print("Table created successfully........")
# 关闭连接
conn.close()
Table created successfully........
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# CREATE TABLE CRICKETERS (
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age INT,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
CREATE TABLE
postgres=#
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# insert into CRICKETERS
(First_Name, Last_Name, Age, Place_Of_Birth, Country) values
('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
INSERT 0 1
postgres=#
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# insert into CRICKETERS
(First_Name, Last_Name, Country) values('Jonathan', 'Trott', 'SouthAfrica');
INSERT 0 1
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
INSERT 0 1
postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
INSERT 0 1
postgres=#
# Filename : example.py # Copyright : 2020 By Lidihuo # Author by : www.lidihuo.com # Date : 2020-08-15 postgres=# SELECT * from CRICKETERS; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+------------- Shikhar | Dhawan | 33 | Delhi | India Jonathan | Trott | | | SouthAfrica Kumara | Sangakkara | 41 | Matale | Srilanka Virat | Kohli | 30 | Delhi | India Rohit | Sharma | 32 | Nagpur | India (5 rows)
导入psycopg2软件包。
通过将用户名,密码,主机(可选的默认值:localhost)和数据库(可选的)作为参数传递给connect()方法来创建连接对象。
通过将false设置为属性autocommit的值来关闭自动提交模式。
psycopg2库的Connection类的cursor()方法返回一个游标对象。使用此方法创建一个游标对象。
然后,通过将INSERT语句作为参数传递给execute()方法来执行INSERT语句。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
import psycopg2
# 简历连接
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
# 设置自动提交
conn.autocommit = True
# 使用cursor()方法创建游标对象
cursor = conn.cursor()
# 准备SQL查询以将记录插入数据库。
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)
VALUES ('Ramya', 'Rama priya', 27, 'F', 9000)''')
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)
VALUES ('Vinay', 'Battacharya', 20, 'M', 6000)''')
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)
VALUES ('Sharukh', 'Sheik', 25, 'M', 8300)''')
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)
VALUES ('Sarmista', 'Sharma', 26, 'F', 10000)''')
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)
VALUES ('Tripthi', 'Mishra', 24, 'F', 6000)''')
# 提交数据
conn.commit()
print("Records inserted........")
# 关闭连接
conn.close()
Records inserted........
SELECT column1, column2, columnN from table_name;
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# CREATE TABLE CRICKETERS (
First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int,
Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
INSERT 0 1
postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
INSERT 0 1
postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
INSERT 0 1
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# SELECT FIRST_NAME, LAST_NAME, COUNtry from CRICKETERS;
first_name | last_name | country
------------+------------+-------------
Shikhar | Dhawan | India
Jonathan | Trott | SouthAfrica
Kumara | Sangakkara | Srilanka
Virat | Kohli | India
Rohit | Sharma | India
(5 rows)
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# SELECT * from CRICKETERS;
first_name | last_name | age | place_of_birth | country
------------+------------+-----+----------------+-------------
Shikhar | Dhawan | 33 | Delhi | India
Jonathan | Trott | 38 | CapeTown | SouthAfrica
Kumara | Sangakkara | 41 | Matale | Srilanka
Virat | Kohli | 30 | Delhi | India
Rohit | Sharma | 32 | Nagpur | India
(5 rows)
postgres=#
fetchall()方法检索查询结果集中的所有行,并将它们作为元组列表返回。(如果我们在检索到几行之后执行此操作,它将返回剩余的行)。
fetchone()方法获取查询结果中的下一行,并将其作为元组返回。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
import psycopg2
# 建立连接
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
# 设置自动提交
conn.autocommit = True
# 使用cursor()方法创建游标对象
cursor = conn.cursor()
# 检索数据
cursor.execute('''SELECT * from EMPLOYEE''')
# 正在从表中获取第一行
result = cursor.fetchone();
print(result)
#Fetching 1st row from the table
result = cursor.fetchall();
print(result)
# 提交数据
conn.commit()
# 关闭连接
conn.close()
('Ramya', 'Rama priya', 27, 'F', 9000.0)
[
('Vinay', 'Battacharya', 20, 'M', 6000.0),
('Sharukh', 'Sheik', 25, 'M', 8300.0),
('Sarmista', 'Sharma', 26, 'F', 10000.0),
('Tripthi', 'Mishra', 24, 'F', 6000.0)
]
SELECT column1, column2, columnN
from table_name
WHERE [search_condition]
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# CREATE TABLE CRICKETERS (
First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int,
Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
INSERT 0 1
postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
INSERT 0 1
postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
INSERT 0 1
# Filename : example.py # Copyright : 2020 By Lidihuo # Author by : www.lidihuo.com # Date : 2020-08-15 postgres=# SELECT * FROM CRICKETERS WHERE AGE > 35; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+------------- Jonathan | Trott | 38 | CapeTown | SouthAfrica Kumara | Sangakkara | 41 | Matale | Srilanka (2 rows) postgres=#
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
import psycopg2
# 建立连接
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
# 设置自动提交
conn.autocommit = True
# 使用cursor()方法创建游标对象
cursor = conn.cursor()
# 删除已存在的表
cursor.execute("DROP TABLE if EXISTS EMPLOYEE")
sql = '''CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) not NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT)'''
cursor.execute(sql)
# 填充表
insert_stmt = "INSERT INTO EMPLOYEE
(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES (%s, %s, %s, %s, %s)"
data = [('Krishna', 'Sharma', 19, 'M', 2000), ('Raj', 'Kandukuri', 20, 'M', 7000),
('Ramya', 'Ramapriya', 25, 'M', 5000),('Mac', 'Mohan', 26, 'M', 2000)]
cursor.executemany(insert_stmt, data)
# 使用where子句检索特定记录
cursor.execute("SELECT * from EMPLOYEE WHERE AGE <23")
print(cursor.fetchall())
# 提交数据
conn.commit()
# 关闭连接
conn.close()
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
[('Krishna', 'Sharma', 19, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)]
SELECT column-list
from table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# CREATE TABLE CRICKETERS (
First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int,
Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
INSERT 0 1
postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
INSERT 0 1
postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
INSERT 0 1
# Filename : example.py # Copyright : 2020 By Lidihuo # Author by : www.lidihuo.com # Date : 2020-08-15 postgres=# SELECT * FROM CRICKETERS ORDER BY AGE; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+------------- Virat | Kohli | 30 | Delhi | India Rohit | Sharma | 32 | Nagpur | India Shikhar | Dhawan | 33 | Delhi | India Jonathan | Trott | 38 | CapeTown | SouthAfrica Kumara | Sangakkara | 41 | Matale | Srilanka (5 rows)es:
# Filename : example.py # Copyright : 2020 By Lidihuo # Author by : www.lidihuo.com # Date : 2020-08-15 postgres=# SELECT * FROM CRICKETERS ORDER BY AGE, FIRST_NAME; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+------------- Virat | Kohli | 30 | Delhi | India Rohit | Sharma | 32 | Nagpur | India Shikhar | Dhawan | 33 | Delhi | India Jonathan | Trott | 38 | CapeTown | SouthAfrica Kumara | Sangakkara | 41 | Matale | Srilanka (5 rows)
# Filename : example.py # Copyright : 2020 By Lidihuo # Author by : www.lidihuo.com # Date : 2020-08-15 postgres=# SELECT * FROM CRICKETERS ORDER BY AGE DESC; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+------------- Kumara | Sangakkara | 41 | Matale | Srilanka Jonathan | Trott | 38 | CapeTown | SouthAfrica Shikhar | Dhawan | 33 | Delhi | India Rohit | Sharma | 32 | Nagpur | India Virat | Kohli | 30 | Delhi | India (5 rows)
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
import psycopg2
# 建立连接
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
# 设置自动提交
conn.autocommit = True
cursor = conn.cursor()
# 删除已存在的表
cursor.execute("DROP TABLE if EXISTS EMPLOYEE")
# 创建一个表
sql = '''CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) not NULL,
LAST_NAME CHAR(20),
AGE INT, SEX CHAR(1),
INCOME INT,
CONTACT INT)'''
cursor.execute(sql)
# 填充表
insert_stmt = "INSERT INTO EMPLOYEE
(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME, CONTACT) VALUES (%s, %s, %s, %s, %s, %s)"
data = [('Krishna', 'Sharma', 26, 'M', 2000, 101),
('Raj', 'Kandukuri', 20, 'M', 7000, 102),
('Ramya', 'Ramapriya', 29, 'F', 5000, 103),
('Mac', 'Mohan', 26, 'M', 2000, 104)]
cursor.executemany(insert_stmt, data)
conn.commit()
# 使用ORDER BY子句检索特定记录
cursor.execute("SELECT * from EMPLOYEE ORDER BY AGE")
print(cursor.fetchall())
# 提交
conn.commit()
# 关闭连接
conn.close()
[('Sharukh', 'Sheik', 25, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F', 10000.0)]
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# CREATE TABLE CRICKETERS (
First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int,
Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
INSERT 0 1
postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
INSERT 0 1
postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
INSERT 0 1
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# UPDATE CRICKETERS SET AGE = 45 WHERE FIRST_NAME = 'Shikhar' ;
UPDATE 1
postgres=#
# Filename : example.py # Copyright : 2020 By Lidihuo # Author by : www.lidihuo.com # Date : 2020-08-15 postgres=# SELECT * FROM CRICKETERS WHERE FIRST_NAME = 'Shikhar'; first_name | last_name | age | place_of_birth | country ------------+-----------+-----+----------------+--------- Shikhar | Dhawan | 45 | Delhi | India (1 row) postgres=#
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# UPDATE CRICKETERS SET AGE = AGE+1;
UPDATE 5
# Filename : example.py # Copyright : 2020 By Lidihuo # Author by : www.lidihuo.com # Date : 2020-08-15 postgres=# SELECT * FROM CRICKETERS; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+------------- Jonathan | Trott | 39 | CapeTown | SouthAfrica Kumara | Sangakkara | 42 | Matale | Srilanka Virat | Kohli | 31 | Delhi | India Rohit | Sharma | 33 | Nagpur | India Shikhar | Dhawan | 46 | Delhi | India (5 rows)
导入psycopg2软件包。
通过将用户名,密码,主机(可选的默认值:localhost)和数据库(可选的)作为参数传递给connect()方法来创建连接对象。
通过将false设置为属性autocommit的值来关闭自动提交模式。
psycopg2库的Connection类的cursor()方法返回一个游标对象。使用此方法创建一个游标对象。
然后,通过将UPDATE语句作为参数传递给execute()方法来执行该语句。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
import psycopg2
# 建立连接
conn = psycopg2.connect (
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
# 设置自动提交
conn.autocommit = True
# 使用cursor()方法创建游标对象
cursor = conn.cursor()
#获取更新之前的所有行
print("Contents of the Employee table: ")
sql = '''SELECT * from EMPLOYEE'''
cursor.execute(sql)
print(cursor.fetchall())
# 更新记录
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M'"
cursor.execute(sql)
print("Table updated...... ")
# 获取更新后的所有行
print("Contents of the Employee table after the update operation: ")
sql = '''SELECT * from EMPLOYEE'''
cursor.execute(sql)
print(cursor.fetchall())
# 提交
conn.commit()
# 关闭连接
conn.close()
Contents of the Employee table:
[
('Ramya', 'Rama priya', 27, 'F', 9000.0),
('Vinay', 'Battacharya', 20, 'M', 6000.0),
('Sharukh', 'Sheik', 25, 'M', 8300.0),
('Sarmista', 'Sharma', 26, 'F', 10000.0),
('Tripthi', 'Mishra', 24, 'F', 6000.0)
]
Table updated......
Contents of the Employee table after the update operation:
[
('Ramya', 'Rama priya', 27, 'F', 9000.0),
('Sarmista', 'Sharma', 26, 'F', 10000.0),
('Tripthi', 'Mishra', 24, 'F', 6000.0),
('Vinay', 'Battacharya', 21, 'M', 6000.0),
('Sharukh', 'Sheik', 26, 'M', 8300.0)
]
DELETE from table_name [WHERE Clause]
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# CREATE TABLE CRICKETERS (
First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int,
Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# insert into CRICKETERS values ('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Virat', 'Kohli', 30, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Rohit', 'Sharma', 32, 'Nagpur', 'India');
INSERT 0 1
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# DELETE from CRICKETERS WHERE LAST_NAME = 'Sangakkara';
DELETE 1
# Filename : example.py # Copyright : 2020 By Lidihuo # Author by : www.lidihuo.com # Date : 2020-08-15 postgres=# SELECT * FROM CRICKETERS; first_name | last_name | age | place_of_birth | country ------------+-----------+-----+----------------+------------- Jonathan | Trott | 39 | CapeTown | SouthAfrica Virat | Kohli | 31 | Delhi | India Rohit | Sharma | 33 | Nagpur | India Shikhar | Dhawan | 46 | Delhi | India (4 rows)
postgres=# DELETE from CRICKETERS;
DELETE 4
# Filename : example.py # Copyright : 2020 By Lidihuo # Author by : www.lidihuo.com # Date : 2020-08-15 postgres=# SELECT * FROM CRICKETERS; first_name | last_name | age | place_of_birth | country ------------+-----------+-----+----------------+--------- (0 rows)
导入psycopg2软件包。
通过将用户名,密码,主机(可选的默认值:localhost)和数据库(可选的)作为参数传递给connect()方法来创建连接对象。
通过将false设置为属性autocommit的值来关闭自动提交模式。
psycopg2库的Connection类的cursor()方法返回一个游标对象。使用此方法创建一个游标对象。
然后,通过将DELETE语句作为参数传递给execute()方法来执行它。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
import psycopg2
# 建立连接
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
# 设置自动提交
conn.autocommit = True
# 使用cursor()方法创建游标对象
cursor = conn.cursor()
# 检索表的内容
print("Contents of the table: ")
cursor.execute('''SELECT * from EMPLOYEE''')
print(cursor.fetchall())
# 删除记录
cursor.execute('''DELETE from EMPLOYEE WHERE AGE > 25''')
# 删除后检索数据
print("Contents of the table after delete operation ")
cursor.execute("SELECT * from EMPLOYEE")
print(cursor.fetchall())
# 提交
conn.commit()
# 关闭连接
conn.close()
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
Contents of the table:
[
('Ramya', 'Rama priya', 27, 'F', 9000.0),
('Sarmista', 'Sharma', 26, 'F', 10000.0),
('Tripthi', 'Mishra', 24, 'F', 6000.0),
('Vinay', 'Battacharya', 21, 'M', 6000.0),
('Sharukh', 'Sheik', 26, 'M', 8300.0)
]
Contents of the table after delete operation:
[
('Tripthi', 'Mishra', 24, 'F', 6000.0),
('Vinay', 'Battacharya', 21, 'M', 6000.0)
]
DROP TABLE table_name;
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# CREATE TABLE CRICKETERS (
First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int,
Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#
postgres=# CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) not NULL, LAST_NAME CHAR(20),
AGE INT, SEX CHAR(1), INCOME FLOAT
);
CREATE TABLE
postgres=#
# Filename : example.py # Copyright : 2020 By Lidihuo # Author by : www.lidihuo.com # Date : 2020-08-15 postgres=# \dt; List of relations Schema | Name | Type | Owner --------+------------+-------+---------- public | cricketers | table | postgres public | employee | table | postgres (2 rows) postgres=#
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# DROP table employee;
DROP TABLE
# Filename : example.py # Copyright : 2020 By Lidihuo # Author by : www.lidihuo.com # Date : 2020-08-15 postgres=# \dt; List of relations Schema | Name | Type | Owner --------+------------+-------+---------- public | cricketers | table | postgres (1 row) postgres=#
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# DROP table employee;
ERROR: table "employee" does not exist
postgres=#
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# DROP table if EXISTS employee;
NOTICE: table "employee" does not exist, skipping
DROP TABLE
postgres=#
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
import psycopg2
# 建立连接
conn = psycopg2.connect(database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432')
# 设置自动提交
conn.autocommit = True
cursor = conn.cursor()
# 删除已存在的表
cursor.execute("DROP TABLE emp")
print("Table dropped... ")
# 提交
conn.commit()
# 关闭连接
conn.close()
# Table dropped...
SELECT column1, column2, columnN
from table_name
LIMIT [no of rows]
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# CREATE TABLE CRICKETERS (
First_Name VARCHAR(255), Last_Name VARCHAR(255),
Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# insert into CRICKETERS values ('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Virat', 'Kohli', 30, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Rohit', 'Sharma', 32, 'Nagpur', 'India');
INSERT 0 1
# Filename : example.py # Copyright : 2020 By Lidihuo # Author by : www.lidihuo.com # Date : 2020-08-15 postgres=# SELECT * FROM CRICKETERS LIMIT 3; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+------------- Shikhar | Dhawan | 33 | Delhi | India Jonathan | Trott | 38 | CapeTown | SouthAfrica Kumara | Sangakkara | 41 | Matale | Srilanka (3 rows)
# Filename : example.py # Copyright : 2020 By Lidihuo # Author by : www.lidihuo.com # Date : 2020-08-15 postgres=# SELECT * FROM CRICKETERS LIMIT 3 OFFSET 2; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+---------- Kumara | Sangakkara | 41 | Matale | Srilanka Virat | Kohli | 30 | Delhi | India Rohit | Sharma | 32 | Nagpur | India (3 rows) postgres=#
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
import psycopg2
# 建立连接
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
# 设置自动提交
conn.autocommit = True
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
# 检索单行
sql = '''SELECT * from EMPLOYEE LIMIT 2 OFFSET 2'''
# 执行查询
cursor.execute(sql)
# 遍历数据
result = cursor.fetchall();
print(result)
# 提交
conn.commit()
# 关闭连接
conn.close()
[('Sharukh', 'Sheik', 25, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F', 10000.0)]
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# CREATE TABLE CRICKETERS (
First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int,
Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
postgres=# insert into CRICKETERS values ('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
postgres=# insert into CRICKETERS values ('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
postgres=# insert into CRICKETERS values ('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
postgres=# insert into CRICKETERS values ('Virat', 'Kohli', 30, 'Delhi', 'India');
postgres=# insert into CRICKETERS values ('Rohit', 'Sharma', 32, 'Nagpur', 'India');
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
postgres=# CREATE TABLE ODIStats (
First_Name VARCHAR(255), Matches INT, Runs INT, AVG FLOAT,
Centuries INT, HalfCenturies INT
);
postgres=# insert into OdiStats values ('Shikhar', 133, 5518, 44.5, 17, 27);
postgres=# insert into OdiStats values ('Jonathan', 68, 2819, 51.25, 4, 22);
postgres=# insert into OdiStats values ('Kumara', 404, 14234, 41.99, 25, 93);
postgres=# insert into OdiStats values ('Virat', 239, 11520, 60.31, 43, 54);
postgres=# insert into OdiStats values ('Rohit', 218, 8686, 48.53, 24, 42);
# Filename : example.py # Copyright : 2020 By Lidihuo # Author by : www.lidihuo.com # Date : 2020-08-15 postgres=# SELECT Cricketers.First_Name, Cricketers.Last_Name, Cricketers.Country, OdiStats.matches, OdiStats.runs, OdiStats.centuries, OdiStats.halfcenturies from Cricketers INNER JOIN OdiStats ON Cricketers.First_Name = OdiStats.First_Name; first_name | last_name | country | matches | runs | centuries | halfcenturies ------------+------------+-------------+---------+-------+-----------+--------------- Shikhar | Dhawan | India | 133 | 5518 | 17 | 27 Jonathan | Trott | SouthAfrica | 68 | 2819 | 4 | 22 Kumara | Sangakkara | Srilanka | 404 | 14234 | 25 | 93 Virat | Kohli | India | 239 | 11520 | 43 | 54 Rohit | Sharma | India | 218 | 8686 | 24 | 42 (5 rows) postgres=#
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
import psycopg2
# 建立连接
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
# 设置自动提交
conn.autocommit = True
cursor = conn.cursor()
# 检索单行
sql = '''SELECT * from EMP INNER JOIN CONTACT ON EMP.CONTACT = CONTACT.ID'''
# 执行查询
cursor.execute(sql)
# 正在从表中获取第一行
result = cursor.fetchall();
print(result)
# 提交
conn.commit()
# 关闭连接
conn.close()
[
('Ramya', 'Rama priya', 27, 'F', 9000.0, 101, 101, 'Krishna@mymail.com', 'Hyderabad'),
('Vinay', 'Battacharya', 20, 'M', 6000.0, 102, 102, 'Raja@mymail.com', 'Vishakhapatnam'),
('Sharukh', 'Sheik', 25, 'M', 8300.0, 103, 103, 'Krishna@mymail.com ', 'Pune'),
('Sarmista', 'Sharma', 26, 'F', 10000.0, 104, 104, 'Raja@mymail.com', 'Mumbai')
]
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
import psycopg2
#establishing the connection
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
#Setting auto commit False
conn.autocommit = True
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
编号 | 方法 & 描述 |
1 |
callproc()
此方法用于调用现有过程PostgreSQL数据库。
|
2 |
close()
此方法用于关闭当前光标对象。
|
3 |
executemany()
此方法接受一系列参数列表list。准备一个MySQL查询并使用所有参数执行它。
|
4 |
execute()
该方法接受一个MySQL查询作为参数并执行给定的查询。
|
5 |
fetchall()
此方法检索查询结果集中的所有行,并将它们作为元组列表返回。(如果我们在检索到几行之后执行此操作,它将返回剩余的行)
|
6 |
fetchone()
此方法获取查询结果中的下一行,并将其作为元组返回。
|
7 |
fetchmany()
此方法与fetchone()相似,但是它检索查询结果集中的下一组行,而不是单行。
|
编号 | 属性 & 描述 |
1 |
description
这是一个只读属性,它返回包含结果集中列说明的列表。
|
2 |
lastrowid
这是一个只读属性,如果表中有任何自动递增的列,它将返回在上一次INSERT或UPDATE操作中为该列生成的值。
|
3 |
rowcount
如果执行SELECT和UPDATE操作,则返回返回/更新的行数。
|
4 |
closed
此属性指定游标是否关闭,如果关闭,则返回true,否则返回false。
|
5 |
connection
这将返回对创建该光标所使用的连接对象的引用。
|
6 |
name
此属性返回游标的名称。
|
7 |
scrollable
此属性指定特定光标是否可滚动。
|