【问题标题】:Insert into a large table in psycopg using a dictionary使用字典插入到 psycopg 中的大表中
【发布时间】:2015-07-28 23:14:21
【问题描述】:

我在数据库中有一个非常大的表(>200 列),我通过 psycopg2 访问它。我有我想作为字典插入的行,列名作为键,值作为值。使用 psycopg2,我想将行插入到表中。

由于有问题的表的列数非常多,我宁愿不手动编写插入语句。如何高效、整齐地插入字典?

【问题讨论】:

    标签: python postgresql psycopg2


    【解决方案1】:

    这是测试表:

    create table testins (foo int, bar int, baz int)
    

    你可以这样写一个sql语句:

    d = dict(foo=10,bar=20,baz=30)
    
    cur.execute(
        "insert into testins (%s) values (%s)" 
            % (','.join(d), ','.join('%%(%s)s' % k for k in d)),
        d)
    

    【讨论】:

    • 好吧,我会的,这就像一个魅力!我认为会有一种更清洁的方法,但现在这已经足够好了。 +1
    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 2016-02-11
    • 2021-07-04
    • 2011-08-07
    • 2010-12-19
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    相关资源
    最近更新 更多