八月 13, 2023
摘要:在本教程中,您将学习如何在 Python 程序中使用psycopg数据库适配器连接到 PostgreSQL 数据库服务器。
目录
安装 psycopg2 模块
首先,访问此处的 psycopg2 软件包。
其次,从终端使用以下命令行:
pip install psycopg2
如果您已经将源码包下载到电脑中,则可以使用setup.py,如下所示:
python setup.py build
sudo python setup.py install
创建一个新数据库
首先,使用任何客户端工具(例如 pgAdmin 或 psql)登录 PostgreSQL 数据库服务器。
其次,使用以下语句在 PostgreSQL 数据库服务器中创建一个名为suppliers的新数据库。
CREATE DATABASE suppliers;
使用 psycopg2 连接到 PostgreSQL 数据库
要连接到suppliers数据库,您可以使用psycopg2模块的connect()函数。
connect()函数创建一个新的数据库会话并返回一个connection类的新实例。通过使用connection对象,您可以创建一个新的cursor对象来执行任何SQL 语句。
要调用connect()函数,您可以将 PostgreSQL 数据库参数指定为连接字符串并将其传递给该函数,如下所示:
conn = psycopg2.connect("dbname=suppliers user=postgres password=postgres")
或者您可以使用关键字参数列表:
conn = psycopg2.connect(
host="localhost",
database="suppliers",
user="postgres",
password="Abcd1234")
以下是连接参数列表:
database:要连接的数据库的名称。user:用于验证的用户名。password:用于验证的密码。host:数据库服务器地址,例如 localhost 或 IP 地址。port:端口号,如果不提供则默认为5432。
为了更方便,您可以使用配置文件来存储所有连接参数。
下图显示了database.ini文件的内容:
[postgresql]
host=localhost
database=suppliers
user=postgres
password=SecurePas$1
通过使用database.ini,您可以在代码迁移到生产环境时更改 PostgreSQL 连接参数,而无需修改代码。
请注意,如果您使用 git,则需要将database.ini添加到.gitignore文件中,以免将敏感信息提交到 github 等公共仓库。该.gitignore文件将是这样的:
database.ini
下面的config()函数会读取database.ini文件并返回连接参数。该config()函数放置在config.py文件中:
#!/usr/bin/python
from configparser import ConfigParser
def config(filename='database.ini', section='postgresql'):
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)
# get section, default to postgresql
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
return db
下面的connect()函数连接到suppliers数据库并打印出 PostgreSQL 数据库版本。
#!/usr/bin/python
import psycopg2
from config import config
def connect():
""" Connect to the PostgreSQL database server """
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
# execute a statement
print('PostgreSQL database version:')
cur.execute('SELECT version()')
# display the PostgreSQL database server version
db_version = cur.fetchone()
print(db_version)
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
if __name__ == '__main__':
connect()
怎么运行的。
- 首先,从
database.ini文件中读取数据库连接参数。 - 接下来,通过调用
connect()函数创建一个新的数据库连接。 - 然后,新建一个
cursor并执行SQL语句来获取 PostgreSQL 数据库版本。 - 之后,通过调用游标对象的
fetchone()方法读取结果集。 - 最后,通过调用
cursor和connection对象的close()方法关闭与数据库服务器的通信。
执行 connect.py 文件
要执行connect.py文件,请使用以下命令:
python connect.py
您将看到以下输出:
Connecting to the PostgreSQL database...
PostgreSQL database version:
('PostgreSQL 12.3, compiled by Visual C++ build 1914, 64-bit',)
Database connection closed.
这意味着您已经成功连接到 PostgreSQL 数据库服务器。
故障排除
如果发生错误,connect()函数将会抛出DatabaseError异常。要查看它是怎么产生的,您可以更改database.ini文件中的连接参数。
例如,如果将 host 参数更改为localhosts,程序将输出以下消息:
Connecting to the PostgreSQL database...
could not translate host name "localhosts" to address: Unknown host
当您将数据库更改为不存在的数据库时,例如supplier,会显示下面的错误消息:
Connecting to the PostgreSQL database...
FATAL: database "supplier" does not exist
如果将 user 参数改为 postgress,则不会认证成功,如下:
Connecting to the PostgreSQL database...
FATAL: password authentication failed for user "postgress"
在本教程中,您学习了如何从 Python 程序连接到 PostgreSQL 数据库服务器。