如何将python列表插入Postgres表 [英] How to insert a python list into Postgres table

查看:227
本文介绍了如何将python列表插入Postgres表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定将python列表中的数据插入PostgreSQL表的最简单方法。

I am trying to determine the simplest way to insert data from a python list into a PostgreSQL table.

我的PostgreSQL表创建如下;

My PostgreSQL table was created as follows;

CREATE TABLE results(Id serial primary key, T0 timestamp, T1 real, T2 real, T3 real, T4 real, Total real, Result text);

我的python列表格式如下;

My python list is formatted as follows;

ResultsList = ['2015-07-20 16:06:05', 0.16, 5.22, 5.81, 0.69, 11.90, 'OK']

我正在使用以下python代码将列表写入结果表;

I am using the following python code to write the list into the results table;

import psycopg2 as dbapi
con = dbapi.connect(database='xxx', user='xxx')
cur = con.cursor()
cur.execute("INSERT into results VALUES (%s);", (ResultsList),)
con.commit()

解释器吐出以下错误;

The interpreter spits out the following error;

Error not all arguments converted during string formatting
Process finished with exit code 0

任何线索都会受到赞赏。

Any clues would be appreciated.

谢谢:)

推荐答案

ResultList 已经是一个序列,您无需尝试将其转换为元组。您真正需要的是在SQL语句中指定正确的值量:

As ResultList is already a sequence, you do not need to try and convert it to a tuple. What you really need is specify the right amount of values in your SQL statement:

cur.execute("INSERT into results(T0, T1, T2, T3, T4, Total, Result) VALUES (%s, %s, %s, %s, %s, %s, %s)", ResultList)

有关它的更多信息,请阅读文档

For more about it, read the docs.

这篇关于如何将python列表插入Postgres表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆