[英]How to check a row already exists before copying the data from csv to postgres using python
我尝试使用python将多个文件中的csv数据转储到postgres中,我成功完成了,但是我想在复制到数据库postgres中之前检查特定行是否已经存在。请检查我的代码
SQL_STATEMENT = """
COPY %s FROM STDIN WITH
CSV
HEADER
DELIMITER AS ','
"""
def process_file(conn, table_name, file_object):
cursor = conn.cursor()
cursor.
cursor.copy_expert(sql=SQL_STATEMENT % table_name, file=file_object)
conn.commit()
cursor.close()
connection = psycopg2.connect("dbname=dataflow user=postgres host=localhost password=root")
try:
process_file(connection, 'mytable', f)
finally:
connection.close()
请建议我该怎么做。
COPY
只是将格式正确的数据加载到表中-无需预处理。 因此,您可以将csv复制到临时表,然后跳过现有表将行插入到表中:
CREATE TABLE temp_t AS SELECT * FROM table_name WHERE false
;
COPY temp_t FROM STDIN WITH
CSV
HEADER
DELIMITER AS ','
;
INSERT INTO table_name
SELECT *
FROM temp_t
EXCEPT
SELECT *
FROM table_name
;
https://www.postgresql.org/docs/current/static/sql-copy.html
COPY FROM将数据从文件复制到表(将数据追加到表中已有的任何内容)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.