python - 将元组插入表中 - psycopg2

标签 python postgresql psycopg2

我试图弄清楚如何将值的元组插入到预定义的表中,而不需要像这样的简单语法:

cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",
...      (100, "abc'def"))

因为我的元组具有正确的值序列,如下所示:

my_tuple = ('D', 'Z107383320', '99501', '995013688', None, '36', '88', '36', '88', 'A', 'F', 'C083', '', 'BARROW', 'ST', '', '0000000605', '0000000605', 'O', 'DOCTORS COLLECTIONS SVC', 'STE', '00000001', '00000001', 'O', 'B', '', '', '020312', 'AK', '020', 'AL', '', '', 'Z10014', 'zip4mst9')

我想知道一些简单的解决方案:-)例如:

cur.execute("INSERT INTO test (*) VALUES (*)",
    ...      (my_tuple))

由于我创建了表模式并且元组具有相同的属性序列,因此我认为这是可能的,而无需将所有参数一一传递给 cur.execute()

最佳答案

使用此表

create table t (
    a int,
    b text
);

省略列列表并将元组作为单个值传递

query = """
    insert into t values %s
    returning *
"""
my_tuple = (2, 'b')

cursor.execute(query, (my_tuple,)) # Notice the comma after my_tuple
rs = cursor.fetchall()
conn.commit()
for row in rs:
    print row

打印

(2, 'b')

完成上述操作后,我认为不明确列出列是不好的做法

关于python - 将元组插入表中 - psycopg2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27193002/

相关文章:

python - 编码德语算法

mysql - 了解类似 MySQL 和 PostgreSQL 数据库中的 EXPLAIN 语句

python - psycopg2 INSERT INTO 执行不返回结果

python - Python Web 应用程序的数据库访问策略

sql - 带表达式的多列索引(PostgreSQL 和 Rails)

python + psycopg2 = 未知类型?

python - 博士 : Getting related posts by ManyToMany category and a tags field

python - PyPandoc 与 PyInstaller 结合使用

Python - 以毫秒为单位的时差对我不起作用

sql - Go 中的 Postgres 列表参数(使用 database/sql 和 pq)