【问题标题】:Creating Multiple Tables Using Psycopg2使用 Psycopg2 创建多个表
【发布时间】:2018-09-23 02:28:29
【问题描述】:

我正在尝试使用 psycopg2 创建多个 (4000) csv 文件并将其导入我的 postgres 数据库。所有 csv 文件都具有相同的列名和类型。我只是不知道如何有效地订购这个。

Python 3.5,Postgre - 9.5.12

问题:

  • .format 无法正常工作(未将 '%s' 替换为 sec_name)
  • 我应该指定要插入的列还是使用 copy_from
  • 我可以再简化一下这个过程吗

    import psycopg2
    import os
    
    conn = psycopg2.connect("dbname=postgres user=postgres")
    cur = conn.curser()
    
    # file_dir == directory containing all the .csv
    sec_files = os.listdir("file_dir")
    
    for files in sec_files:
    
        # Cuts off all whitespace and .csv
        sec_name = ''.join(files.split())[:-4]
    
        cur.execute(''' CREATE TABLE '%s' (
            Date NOT NULL UNIQUE DATE PRIMARY KEY
            col2 FLOAT NOT NULL
            col3 FLOAT NOT NULL
            col4 FLOAT NOT NULL
            col5 FLOAT NOT NULL
            col6 FLOAT NOT NULL
            col7 INTEGER  NOT NULL )''').format(sec_name)
         print("Table created ",sec_name)
    
        with open(os.path.abspath(files),'r') as f:
            next(f)
            for row in reader:
                 cur.copy_from(f,sec_name, sep=',')
    
        conn.commit()
        print('Data inserted into ', sec_name, ' completed')
    

【问题讨论】:

  • 不要使用format,你很容易发生SQL注入,如果你想插入表名,你需要psycopg2.extensions中的AsIs模块,你也在尝试做4000张桌子?似乎有些不对劲......
  • 我不明白如何使用 psycopg2.extensions.AsIs。是的 4000。
  • 如果您要制作 4000 个表,您的设计模式就有问题,只是说...

标签: python postgresql psycopg2


【解决方案1】:

重新格式化您的代码,并没有改变您插入数据的方式,因为这将是更多的重构,但鉴于您所展示的内容,这将是执行您提供的代码的正确方法。

import os
import psycopg2
from psycopg2.extensions import AsIs

query = """
        CREATE TABLE %(table)s (
            Date NOT NULL UNIQUE DATE PRIMARY KEY
            col2 FLOAT NOT NULL
            col3 FLOAT NOT NULL
            col4 FLOAT NOT NULL
            col5 FLOAT NOT NULL
            col6 FLOAT NOT NULL
            col7 INTEGER  NOT NULL)
        """

sec_files = os.listdir('file_dir')
conn = psycopg2.connect('dbname=postgres user=postgres')

with conn.cursor() as cursor:
    for file in sec_files:
        name = os.path.basename(file).split('.')[0]
        cursor.execute(query, {'table': AsIs(name)})
        print('Table created', name)

        with open(os.path.abspath(file), 'r') as fin:
            next(f)
            cursor.copy_from(f, name, sep=',')
            print('Data inserted into ', name, ' complete')

【讨论】:

    猜你喜欢
    • 2020-10-29
    • 1970-01-01
    • 2022-01-09
    • 2020-07-05
    • 2017-11-01
    • 1970-01-01
    • 2019-04-01
    • 2020-09-01
    • 1970-01-01
    相关资源
    最近更新 更多