Python中的Psycopg2模块介绍
Psycopg是Python中最流行的 PostgreSQL 适配器。它的工作原理是Python DB API 2.0 的整个实现以及线程安全(同一连接由多个线程共享)。它旨在执行大量多线程应用程序,这些应用程序通常会创建和销毁大量游标并同时进行大量 INSERTS 或 UPDATES。 Psycopg 具有客户端和服务器端游标、异步通信和通知功能。 Psycopg 2 对 Unicode 和Python 3 都友好。
安装:
当前的 psycopg2 实现支持:
- Python版本从 3.6 到 3.10
- PostgreSQL 服务器版本从 7.4 到 14
- 从 9.1 开始的 PostgreSQL 客户端库版本
- pgAdmin 4
对于大多数可用的操作系统,安装此包的最快方法是通过 PyPI 库中提供的 wheel 包。我们必须确保使用最新版本的 pip,可以在终端中使用以下命令进行更新。
$ pip install -U pip
$ pip install psycopg2-binary
这将安装不需要构建或运行时先决条件的模块的预编译二进制版本。然后我们可以按照通常的方式导入 psycopg2 包:
基本模块用法:
Psycopg 的基本用途是为所有数据库适配器实现 DB API 2.0 协议。这是基本命令的基本交互会话。
示例 1 :在Python程序和 PostgreSQL 数据库之间建立连接的程序。
Python3
import psycopg2
DB_NAME = "tkgafrwp"
DB_USER = "tkgafrwp"
DB_PASS = "iYYtLAXVbid-i6MV3NO1EnU-_9SW2uEi"
DB_HOST = "tyke.db.elephantsql.com"
DB_PORT = "5432"
try:
conn = psycopg2.connect(database=DB_NAME,
user=DB_USER,
password=DB_PASS,
host=DB_HOST,
port=DB_PORT)
print("Database connected successfully")
except:
print("Database not connected successfully")
Python3
import psycopg2
DB_NAME = "tkgafrwp"
DB_USER = "tkgafrwp"
DB_PASS = "iYYtLAXVbid-i6MV3NO1EnU-_9SW2uEi"
DB_HOST = "tyke.db.elephantsql.com"
DB_PORT = "5432"
conn = psycopg2.connect(database=DB_NAME,
user=DB_USER,
password=DB_PASS,
host=DB_HOST,
port=DB_PORT)
print("Database connected successfully")
cur = conn.cursor() # creating a cursor
# executing queries to create table
cur.execute("""
CREATE TABLE Employee
(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
EMAI TEXT NOT NULL
)
""")
# commit the changes
conn.commit()
print("Table Created successfully")
Python3
import psycopg2
DB_NAME = "tkgafrwp"
DB_USER = "tkgafrwp"
DB_PASS = "iYYtLAXVbid-i6MV3NO1EnU-_9SW2uEi"
DB_HOST = "tyke.db.elephantsql.com"
DB_PORT = "5432"
conn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS,
host=DB_HOST, port=DB_PORT)
print("Database connected successfully")
cur = conn.cursor()
cur.execute("""
INSERT INTO Employee (ID,NAME,EMAI) VALUES
(1,'Alan Walker','awalker@gmail.com'),
(2,'Steve Jobs','sjobs@gmail.com')
""")
conn.commit()
conn.close()
Python3
from mysqlx import Row
import psycopg2
DB_NAME = "tkgafrwp"
DB_USER = "tkgafrwp"
DB_PASS = "iYYtLAXVbid-i6MV3NO1EnU-_9SW2uEi"
DB_HOST = "tyke.db.elephantsql.com"
DB_PORT = "5432"
conn = psycopg2.connect(database=DB_NAME,
user=DB_USER,
password=DB_PASS,
host=DB_HOST,
port=DB_PORT)
print("Database connected successfully")
cur = conn.cursor()
cur.execute("SELECT * FROM Employee")
rows = cur.fetchall()
for data in rows:
print("ID :" + str(data[0]))
print("NAME :" + data[1])
print("EMAIL :" + data[2])
print('Data fetched successfully')
conn.close()
Python3
from turtle import st
from mysqlx import Row
import psycopg2
DB_NAME = "tkgafrwp"
DB_USER = "tkgafrwp"
DB_PASS = "iYYtLAXVbid-i6MV3NO1EnU-_9SW2uEi"
DB_HOST = "tyke.db.elephantsql.com"
DB_PORT = "5432"
conn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS,
host=DB_HOST, port=DB_PORT)
print("Database connected successfully")
cur = conn.cursor()
cur.execute("UPDATE Employee set EMAI = 'updated@gmail.com' WHERE ID =1 ")
conn.commit()
print("Data updated Successfully")
print("Total row affected "+str(cur.rowcount))
conn.close()
Python3
from turtle import st
from mysqlx import Row
import psycopg2
DB_NAME = "tkgafrwp"
DB_USER = "tkgafrwp"
DB_PASS = "iYYtLAXVbid-i6MV3NO1EnU-_9SW2uEi"
DB_HOST = "tyke.db.elephantsql.com"
DB_PORT = "5432"
conn = psycopg2.connect(database=DB_NAME,user=DB_USER,password=DB_PASS,
host=DB_HOST,port=DB_PORT)
print("Database connected successfully")
cur = conn.cursor()
cur.execute("DELETE FROM Employee WHERE ID =1 ")
conn.commit()
print("Data deleted Successfully")
print("Total row affected "+str(cur.rowcount))
conn.close()
示例 2:使用Python创建表
Python3
import psycopg2
DB_NAME = "tkgafrwp"
DB_USER = "tkgafrwp"
DB_PASS = "iYYtLAXVbid-i6MV3NO1EnU-_9SW2uEi"
DB_HOST = "tyke.db.elephantsql.com"
DB_PORT = "5432"
conn = psycopg2.connect(database=DB_NAME,
user=DB_USER,
password=DB_PASS,
host=DB_HOST,
port=DB_PORT)
print("Database connected successfully")
cur = conn.cursor() # creating a cursor
# executing queries to create table
cur.execute("""
CREATE TABLE Employee
(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
EMAI TEXT NOT NULL
)
""")
# commit the changes
conn.commit()
print("Table Created successfully")
示例 3:向表中插入数据:
Python3
import psycopg2
DB_NAME = "tkgafrwp"
DB_USER = "tkgafrwp"
DB_PASS = "iYYtLAXVbid-i6MV3NO1EnU-_9SW2uEi"
DB_HOST = "tyke.db.elephantsql.com"
DB_PORT = "5432"
conn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS,
host=DB_HOST, port=DB_PORT)
print("Database connected successfully")
cur = conn.cursor()
cur.execute("""
INSERT INTO Employee (ID,NAME,EMAI) VALUES
(1,'Alan Walker','awalker@gmail.com'),
(2,'Steve Jobs','sjobs@gmail.com')
""")
conn.commit()
conn.close()
将参数传递给 SQL 查询
Python变量通过 Psycopg 转换为 SQL 值, Python确定用于将对象转换为适合 PostgreSQL 的字符串表示的函数。将参数传递给 SQL 语句发生在使用 %s 作为占位符的函数中,例如 cursor.execute()到 SQL 语句中。
示例 4:从数据库中获取数据并将其显示到终端中。
Python3
from mysqlx import Row
import psycopg2
DB_NAME = "tkgafrwp"
DB_USER = "tkgafrwp"
DB_PASS = "iYYtLAXVbid-i6MV3NO1EnU-_9SW2uEi"
DB_HOST = "tyke.db.elephantsql.com"
DB_PORT = "5432"
conn = psycopg2.connect(database=DB_NAME,
user=DB_USER,
password=DB_PASS,
host=DB_HOST,
port=DB_PORT)
print("Database connected successfully")
cur = conn.cursor()
cur.execute("SELECT * FROM Employee")
rows = cur.fetchall()
for data in rows:
print("ID :" + str(data[0]))
print("NAME :" + data[1])
print("EMAIL :" + data[2])
print('Data fetched successfully')
conn.close()
示例 5:更新数据库中的数据。
Python3
from turtle import st
from mysqlx import Row
import psycopg2
DB_NAME = "tkgafrwp"
DB_USER = "tkgafrwp"
DB_PASS = "iYYtLAXVbid-i6MV3NO1EnU-_9SW2uEi"
DB_HOST = "tyke.db.elephantsql.com"
DB_PORT = "5432"
conn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS,
host=DB_HOST, port=DB_PORT)
print("Database connected successfully")
cur = conn.cursor()
cur.execute("UPDATE Employee set EMAI = 'updated@gmail.com' WHERE ID =1 ")
conn.commit()
print("Data updated Successfully")
print("Total row affected "+str(cur.rowcount))
conn.close()
示例 6:从数据库中删除数据。
Python3
from turtle import st
from mysqlx import Row
import psycopg2
DB_NAME = "tkgafrwp"
DB_USER = "tkgafrwp"
DB_PASS = "iYYtLAXVbid-i6MV3NO1EnU-_9SW2uEi"
DB_HOST = "tyke.db.elephantsql.com"
DB_PORT = "5432"
conn = psycopg2.connect(database=DB_NAME,user=DB_USER,password=DB_PASS,
host=DB_HOST,port=DB_PORT)
print("Database connected successfully")
cur = conn.cursor()
cur.execute("DELETE FROM Employee WHERE ID =1 ")
conn.commit()
print("Data deleted Successfully")
print("Total row affected "+str(cur.rowcount))
conn.close()
Psycopg 的主要入口点是:
- connect()函数创建一个新的数据库会话并返回一个新的连接实例。
- 类连接包含一个数据库会话。它允许:
- 创建新的游标实例
- 使用 commit() 或 rollback() 方法终止事务。
- 游标允许与数据库交互:
- 使用 execute() 和 executemany() 方法向数据库发送命令。
- 使用 fetchone()、fetchmany()、fetchall() 等方法或通过迭代从数据库中检索数据。