环境准备
在开始之前,请确保你已经安装了Python和PostgreSQL数据库。为了能够从Python连接到PostgreSQL,你需要安装psycopg2
库。可以通过以下命令安装:
pip install psycopg2
#如果报错,安装下面这个
pip install psycopg2-binary
连接到PostgreSQL数据库
在进行数据写入之前,我们需要建立与PostgreSQL数据库的连接。以下是连接数据库的基本代码:
import psycopg2
from psycopg2 import Error
def create_connection():
"""创建数据库连接"""
try:
connection = psycopg2.connect(
host="localhost",
database="your_database_name", # 替换为你的数据库名
user="your_username", # 替换为你的用户名
password="your_password" # 替换为你的密码
)
print("PostgreSQL Database connection successful")
return connection
except Error as e:
print(f"The error '{e}' occurred")
return None
插入数据
一旦建立了连接,我们就可以开始插入数据了。以下是一个插入数据的例子,假设我们有一个名为employees
的表,我们想要向其中插入员工信息:
def insert_employee(conn, employee):
"""插入员工信息到数据库"""
query = "INSERT INTO employees (name, position, department) VALUES (%s, %s, %s)"
cursor = conn.cursor()
try:
cursor.execute(query, employee)
conn.commit() # 提交事务
print("Employee inserted successfully")
except Error as e:
print(f"The error '{e}' occurred")
finally:
cursor.close()
# 插入数据的示例
employee = ('John Doe', 'Software Engineer', 'Development')
conn = create_connection()
if conn is not None:
insert_employee(conn, employee)
conn.close()
批量插入数据
在实际应用中,我们可能需要批量插入多条数据。以下是批量插入数据的示例:
def insert_employees(conn, employees):
"""批量插入员工信息"""
query = "INSERT INTO employees (name, position, department) VALUES (%s, %s, %s)"
cursor = conn.cursor()
try:
for employee in employees:
cursor.execute(query, employee)
conn.commit() # 提交事务
print("Employees inserted successfully")
except Error as e:
print(f"The error '{e}' occurred")
finally:
cursor.close()
# 批量插入数据的示例
employees = [
('Jane Doe', 'Project Manager', 'Development'),
('Alice Johnson', 'Data Analyst', 'Analytics'),
('Mike Smith', 'UX Designer', 'Design')
]
conn = create_connection()
if conn is not None:
insert_employees(conn, employees)
conn.close()
完整代码
以下是整合了上述例子的完整Python脚本,用于连接PostgreSQL数据库并执行数据插入操作:
import psycopg2
from psycopg2 import Error
# 创建数据库连接
def create_connection():
"""创建数据库连接"""
try:
connection = psycopg2.connect(
host="localhost",
database="your_database_name", # 替换为你的数据库名
user="your_username", # 替换为你的用户名
password="your_password" # 替换为你的密码
)
print("PostgreSQL Database connection successful")
return connection
except Error as e:
print(f"The error '{e}' occurred")
return None
# 插入员工信息到数据库
def insert_employee(conn, employee):
"""插入员工信息"""
query = "INSERT INTO employees (name, position, department) VALUES (%s, %s, %s)"
cursor = conn.cursor()
try:
cursor.execute(query, employee)
conn.commit() # 提交事务
print("Employee inserted successfully")
except Error as e:
print(f"The error '{e}' occurred")
finally:
cursor.close()
# 批量插入员工信息
def insert_employees(conn, employees):
"""批量插入员工信息"""
query = "INSERT INTO employees (name, position, department) VALUES (%s, %s, %s)"
cursor = conn.cursor()
try:
for employee in employees:
cursor.execute(query, employee)
conn.commit() # 提交事务
print("Employees inserted successfully")
except Error as e:
print(f"The error '{e}' occurred")
finally:
cursor.close()
# 主程序
if __name__ == '__main__':
# 插入单条数据
employee = ('John Doe', 'Software Engineer', 'Development')
conn = create_connection()
if conn is not None:
insert_employee(conn, employee)
conn.close()
# 批量插入数据
employees = [
('Jane Doe', 'Project Manager', 'Development'),
('Alice Johnson', 'Data Analyst', 'Analytics'),
('Mike Smith', 'UX Designer', 'Design')
]
conn = create_connection()
if conn is not None:
insert_employees(conn, employees)
conn.close()
在运行这段代码之前,请确保你已经替换了create_connection
函数中的database
、user
和password
的值,使其与你自己的PostgreSQL数据库配置相匹配。同时,确保你的PostgreSQL服务正在运行,并且employees
表存在于你的数据库中,且表结构包含name
、position
和department
这三个字段。
这段代码首先尝试连接到PostgreSQL数据库,然后执行插入操作来向employees
表插入一条员工记录,并提交事务。接着,它尝试批量插入多条员工记录,并提交事务。最后,代码会关闭数据库连接。如果在任何步骤中遇到错误,它会打印错误信息。