【问题标题】:how to insert rows from a csv to specific columns in an existing table in postgres+python?如何将csv中的行插入postgres + python中现有表中的特定列?
【发布时间】:2018-01-13 20:52:47
【问题描述】:

我是 python 的新手,特别是烧瓶,正在开发个人网络应用程序 我在我的 html 代码中从用户那里获取一个 csv 文件,我想读取每一行,并使用 python panda flask 将这一行中的特定单元格插入到 postgres 中现有表中的特定列中。

收到此错误

IndexError:字符串索引超出范围

我的代码是这样的

    bkfile = request.files['bk_file']
    conn = psycopg2.connect("host=localhost dbname=saveory user=user 
    password=pass")
    cur = conn.cursor()
    df=pd.read_csv(bkfile)
    for row in df:
        if not row[5]:
            query = ("INSERT INTO main_table(column2, column4, column5, column6) VALUES (row[1], row[3], row[6], 'charge')")
            cur.execute(query)
        if not row[6]:
            query = ("INSERT INTO main_table(column2, column4, column5, column6) VALUES (row[1], row[3], row[5], 'credit')")
            cur.execute(query)
conn.commit()

tnx 帮你!

【问题讨论】:

    标签: python postgresql csv flask


    【解决方案1】:

    除非存在这样的元素,否则您不能引用列表/字符串中的元素 - 即 row[5] 将引发异常,除非行中至少有 6 个元素。

    您的意思可能类似于:if len(row) < 6

    【讨论】:

    • 感谢您的帮助。按行 [5],我想要当前行的第 5 列的内容。这个语法不对吗?
    猜你喜欢
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 2023-01-10
    • 2021-12-10
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多