读取CSV以使用Python将数据插入Postgres SQL

时间:2016-10-19 15:47:57

标签: python postgresql csv psycopg2

我想读一个csv文件,用Python将数据插入到postgres SQL中 但我有这些错误:

  cursor.execute(passdata)
  psycopg2.IntegrityError: duplicate key value violates unique constraint "prk_constraint_project"
  DETAIL:  Key (project_code)=(%s) already exists.

我的代码是:

  clinicalCSVINSERT = open(clinicalname, 'r')
  reader = csv.reader(clinicalCSVINSERT, delimiter='\t')
  passdata = "INSERT INTO project (project_code, program_name ) VALUES ('%s', '%s')";
  cursor.execute(passdata)
  conn.commit()` 

这个错误是什么意思? 是否有可能有一个工作脚本?

1 个答案:

答案 0 :(得分:2)

您的代码存在的直接问题是您尝试包含文字%s。由于您可能不止一次地运行它,因此您在该唯一列中已经有文字%s,因此例外。

必须将包含在iterable中的值作为参数传递给execute方法。 %s只是一个价值占有者。

passdata = """
    INSERT INTO project (project_code, program_name ) 
    VALUES (%s, %s)
"""
cursor.execute(passdata, (the_project_code, the_program_name))

不要引用%s。如有必要,Psycopg会这样做。

由于您的代码不包含循环,因此只会从csv插入一行。有一些模式可以插入整个文件。如果要求允许只使用更简单,更快的copy_from