通过python向Postgres插入数据时出错
我正在执行一个python脚本,在将数据插入PostgreSQL数据库时出现以下错误 对如何处理这件事有什么建议吗通过python向Postgres插入数据时出错,python,python-3.x,Python,Python 3.x,我正在执行一个python脚本,在将数据插入PostgreSQL数据库时出现以下错误 对如何处理这件事有什么建议吗 cur.execute(cmd, str(api_response)) TypeError: not all arguments converted during string formatting 此外,我还想将datetime添加到此表中,如果表模式中有时间戳,如何将当前时间插入表中,以及需要做哪些更改 下面是示例脚本 import psycopg2 def db_con
cur.execute(cmd, str(api_response))
TypeError: not all arguments converted during string formatting
此外,我还想将datetime添加到此表中,如果表模式中有时间戳,如何将当前时间插入表中,以及需要做哪些更改
下面是示例脚本
import psycopg2
def db_connect():
try:
DSN = "dbname='postgres' user='postgres' host='localhost' password='postgres' port='5432'"
conn = psycopg2.connect(DSN)
return conn
except (Exception, psycopg2.Error) as error:
print('database connection failed')
quit()
start_dt = date(2020, 10, 1)
end_dt = datetime.date(datetime.now())
connection=db_connect()
cur = connection.cursor()
cmd="""INSERT into email_stats(raw_data) SELECT %s"""
for dt in daterange(start_dt, end_dt):
start_date = dt.strftime("%Y-%m-%d")
end_date = dt.strftime("%Y-%m-%d")
try:
api_response = api_instance.get_aggregated_smtp_report(start_date=start_date, end_date=end_date)
cur.execute(cmd, str(api_response))
connection.commit()
表模式
CREATE TABLE email_stats
(raw_data text COLLATE pg_catalog."default")
WITH (OIDS = FALSE)TABLESPACE pg_default;
API响应示例
Database connected...
Cursor initiated
Connection succesful
{'blocked': 0,
'clicks': 0,
'delivered': 140,
'hard_bounces': 0,
'invalid': 0,
'opens': 7501,
'range': '2020-10-29|2020-10-29',
'requests': 4,
'soft_bounces': 0,
'spam_reports': 1,
'unique_clicks': 0,
'unique_opens': 3502,
'unsubscribed': 9}
Traceback (most recent call last):
File "/Users/user2/Downloads/bu.py", line 54, in <module>
cur.execute(cmd, str(api_response))
TypeError: not all arguments converted during string formatting
数据库已连接。。。
光标启动
连接成功
{'s':0,
“单击”:0,
“已交付”:140,
“硬反弹”:0,
“无效”:0,
“打开”:7501,
“范围”:“2020-10-29 | 2020-10-29”,
“请求”:4,
“软反弹”:0,
“垃圾邮件报告”:1,
“唯一单击”:0,
“唯一打开”:3502,
“取消订阅”:9}
回溯(最近一次呼叫最后一次):
文件“/Users/user2/Downloads/bu.py”,第54行,在
当前执行(cmd,str(api_响应))
TypeError:在字符串格式化过程中并非所有参数都已转换
对于大多数DB API,参数必须作为可重用而不是标量传递。因此,在listcur.execute(cmd,[str(api_响应)])
或tuplecur.execute(cmd,(str(api_响应)))
@Parfait中传递参数非常感谢:)有效。从技术上讲,你的问题实际上是一个重复的问题,被问了多种类型的问题,但都有相同的错误。在问之前一定要先问清楚。