Python 入门 psycopg2-PostgreSQL
本教程中,我们将学习如何使用 PostgreSQL 和 Python。应在学习本教程前安装特定内容。我们来安装它们。
根据 指南 安装 PostgreSQL。
安装用于连接和使用 PostgreSQL 的 Python 模块 psycopg2。运行命令以安装它。
pip install psycopg2
现在,打开 pgAdmin。并创建一个示例数据库。接下来,按照以下步骤开始数据库操作。
- 导入 psycopg2 模块。
- 将数据库名称、用户名和密码存储在不同的变量中。
- 使用 psycopg2.connect(database=name, user=name, password=password) 方法创建到数据库的连接。
- 实例化一个游标对象以执行 SQL 命令。
- 使用 cursor.execute(query) 方法创建查询并执行它们。
- 而且,使用 cursor.fetchall() 方法获取信息(如果可用)。
- 使用 connection.close() 方法关闭连接。
示例
# importing the psycopg2 module
import psycopg2
# storing all the information
database = 'testing'
user = 'postgres'
password = 'C&o%Z?bc'
# connecting to the database
connection = psycopg2.connect(database=database, user=user, password=password)
# instantiating the cursor
cursor = connection.cursor()
# query to create a table
create_table = "CREATE TABLE testing_members (id SERIAL PRIMARY KEY, name VARCH
25) NOT NULL)"
# executing the query
cursor.execute(create_table)
# sample data to populate the database table
testing_members = ['Python', 'C', 'JavaScript', 'React', 'Django']
# query to populate the table testing_members
for testing_member in testing_members:
populate_db = f"INSERT INTO testing_members (name) VALUES ('{testing_member
cursor.execute(populate_db)
# saving the changes to the database
connection.commit()
# query to fetch all
fetch_all = "SELECT * FROM testing_members"
cursor.execute(fetch_all)
# fetching all the rows
rows = cursor.fetchall()
# printing the data
for row in rows:
print(f"{row[0]} {row[1]}")
# closing the connection
connection.close()输出
如果您运行上述代码,将会得到以下结果。
1 Python 2 C 3 JavaScript 4 React 5 Django
结论
如果对本教程有任何疑问,敬请在评论区中提出。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP