首页 > 解决方案 > 如何在 PostgreSQL 表中插入具有匹配列名的 csv 数据行?

问题描述

我正在编写一个代码来将匹配列的行从 CSV 复制到 PostgreSQL 表。我正在使用python和qgis。代码如下

    connection=psycopg2.connect(host=host, port=port, dbname=dbname, user=name_user, password=password)        
    cursor = connection.cursor ()        
    cursor.execute("""SELECT Count(*) FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'table'""")
    csv1 = pd.read_csv(self.dlg.lineEdit_5.text())
    csvfile = open(self.dlg.lineEdit_5.text(),'r')
    columnnames = csv1.columns.values
  
    table=self.dlg.comboBox.currentText()
    table_name = table.strip(' ' ' ')
    self.dlg.lineEdit_6.setText(str(table))
    with open(self.dlg.lineEdit_5.text(), 'r') as f:
        reader = csv.reader(f)
        next(reader) # This skips the 1st row which is the header.
          
        for x in columnnames:
            column = x.strip(' ' ' ')
            #self.dlg.lineEdit_6.setText(str(column))
            sql_insert = """INSERT INTO table_name(x) VALUES(%s)"""
            for record in reader:
                cursor.execute(sql_insert,[record])
                connection.commit()

我收到如下错误

        psycopg2.errors.UndefinedTable: relation "table_name" does not exist
         LINE 1: INSERT INTO table_name(x) VALUES(ARRAY['501','mah','A'])

如何解决此错误?table_name 存在于数据库中。

标签: python-3.xpostgresqlpsycopg2qgispyqgis

解决方案


这是一个愚蠢的错误。我从 python 代码中的变量中获取表名。因此,查询需要编写如下。

    table=self.dlg.comboBox.currentText()
    table_name = table.strip(' ' ' ') 
    sql_insert = """INSERT INTO %(table_name)s (x) VALUES(%s);""" 
      cursor.execute(sql_insert,[value])         
      connection.commit()

推荐阅读