使用psycopg2和python 3.4将数据从csv插入postgres表

时间:2017-03-07 14:25:39

标签: python postgresql python-3.x psycopg2

我有一个带有以下结构的postgres表

CREATE TABLE edmonton.permit
                            (permit_date text,
                             permit_number text,
                             year numeric,
                             month_number integer,
                             report_permit_date text,
                             job_category text,
                             address text,
                             legal_description text,
                             neighbourhood text,
                             neighbourhood_number text,
                             job_description text,
                             building_type text,
                             work_type text,
                             floor_area numeric,
                             construction_value integer,
                             zoning text,
                             units_added numeric,
                             latitude double precision,
                             longitude double precision,
                             location text,
                             count integer

我正在尝试从相对路径读取csv文件并将数据导入到postgres表中,如下所示

                with open(file) as f:
                reader = csv.reader(f, delimiter=',')
                next(reader, None)
                for row in reader:
                    cur.execute("INSERT INTO edmonton.{}(permit_date, permit_number, year, month_number, report_permit_date, job_category, address, legal_description, neighbourhood, neighbourhood_number, job_description, building_type, work_type, floor_area, construction_value, zoning, units_added, latitude, longitude, location, count) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)".format(permit),row)
                    con.commit()

我收到以下错误

Invalid literals for numeric datatype.

使用python3.4,数字,整数,双精度应该使用哪个占位符?

1 个答案:

答案 0 :(得分:1)

这可能有助于缩小范围。将尝试格式化每个字段并对导致问题的字段给出错误。

with open(file) as f:
reader = csv.reader(f, delimiter=',')
next(reader, None)
for row in reader:
    for item in row:
        print cursor.mogrify("%s", (item,))