如何在 PostgreSql 数据库中插入 Python 元组?

pythonserver side programmingprogramming更新于 2025/7/2 3:56:17

PostgreSql 数据库默认安装在端口号 5432 上。通过安装 psycopg2 模块提供 PostgreSql 的 Python 接口。假设有测试数据库和员工表,表中包含fname、sname、age、gender和salary字段。

首先建立连接,并通过Python脚本中的以下语句获取游标对象。

import psycopg2
conn = psycopg2.connect(database = "test", user = "postgres", password = "pass123", host = "localhost", port = "5432")
cur = conn.cursor()

员工表中要插入的数据以元组对象的形式存储

t1=('Mac', 'Mohan', 20, 'M', 2000)

接下来使用此元组设置插入查询

sql="insert into employee values(%s,%s,%d,%s,%d)" %t1

现在使用游标对象执行此查询

cursor.execute(sql)

此语句的结果是 employee 表将显示其中添加的新记录。


相关文章


有用资源