【问题标题】:Inserting row with many columns of different datatypes into postgresql with psycopg2使用 psycopg2 将具有许多不同数据类型的列的行插入到 postgresql 中
【发布时间】:2023-04-08 21:47:01
【问题描述】:

这个问题是关于将一​​条记录的插入 SQL 语句构造到一个有很多列(在我的例子中是 135 列)的表中。

在任何人分析为什么有这么多列之前,让我先简化一下:我试图以尽可能少的修改来提取原始数据,原始数据有 135 列。

现在,按照this 指南,插入记录的简单方法是:

import psycopg2

con = psycopg2.connect(<your db credentials>)
cur = con.cursor()

cur.execute("INSERT INTO STUDENT (ADMISSION,NAME,AGE,COURSE,DEPARTMENT) VALUES (3420, 'John', 18, 'Computer Science', 'ICT')");

另外请注意,如果我们在不省略任何列的情况下插入记录,那么我们不需要指定列名more details here

cur.execute("INSERT INTO STUDENT VALUES (3420, 'John', 18, 'Computer Science', 'ICT')");

如果我们的数据保存在 python 变量中,psycopg2 允许我们这样做:

admission = 3420
name = 'John'
age = 18
course = 'Computer Science'
department = 'ICT'
cur.execute("INSERT INTO STUDENT VALUES (%s, %s, %s, %s, %s)",(admission, name, age, course, department))

但是插入具有 135 个属性的记录的推荐方法是什么? 虽然我的直觉是自己构建 SQL 查询,但文档确实指出:

警告永远,永远,永远不要使用 Python 字符串连接 (+) 或字符串参数插值 (%) 将变量传递给 SQL 查询字符串。甚至在枪口下也没有。

所以,总结一下:如何将具有任意列数的原始数据提取到表中?

【问题讨论】:

    标签: python-3.x postgresql psycopg2


    【解决方案1】:

    看起来使用psycopg2.sql.Placeholder 可以解决问题。

    从例子:

    >>> names = ['foo', 'bar', 'baz']
    
    >>> q1 = sql.SQL("insert into table ({}) values ({})").format(
    ...     sql.SQL(', ').join(map(sql.Identifier, names)),
    ...     sql.SQL(', ').join(sql.Placeholder() * len(names)))
    >>> print(q1.as_string(conn))
    insert into table ("foo", "bar", "baz") values (%s, %s, %s)
    
    >>> q2 = sql.SQL("insert into table ({}) values ({})").format(
    ...     sql.SQL(', ').join(map(sql.Identifier, names)),
    ...     sql.SQL(', ').join(map(sql.Placeholder, names)))
    >>> print(q2.as_string(conn))
    insert into table ("foo", "bar", "baz") values (%(foo)s, %(bar)s, %(baz)s)
    

    因此我想我可以这样做:

    cols = ['ADMISSION', 'NAME', 'AGE', 'COURSE', 'DEPARTMENT']
    row = [admission, name, age, course, department]
    insertion_query = sql.SQL("INSERT INTO STUDENT VALUES ({})").format(sql.SQL(', ').join(map(sql.Placeholder() * len(cols)))
    
    cur.execute(insertion_query, row)
    

    【讨论】:

      猜你喜欢
      • 2017-06-30
      • 1970-01-01
      • 2022-11-28
      • 2013-05-12
      • 1970-01-01
      • 2017-02-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-22
      相关资源
      最近更新 更多