python-3.x - 如何在 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 代码中的变量中获取表名。因此,查询需要编写如下。
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()
推荐阅读
- xml - 使用 XML::Simple 将 XML 解析为散列时如何保留前导空格
- c# - 实体配置问题 INSERT 语句与 FOREIGN KEY 约束冲突
- c# - 如何使 appsettings.json 配置在项目而不是 bin 文件夹中?
- dataframe - 如何为 DataFrame 中的每一行返回一个 DataFrame 并将结果连接到一个 DataFrame 中?
- sql - SQL:跨两列的唯一值
- go - 声明函数类型的方式有什么区别?
- python - Django 错误 TypeError: __init__() 接受 1 个位置参数,但给出了 2 个
- python - 如何使用同时支持简单类型和属性的字段声明协议?
- apache-atlas - Apache Atlas 中两种不同类型之间的名称关系链接
- python-3.x - 使用 Pandas 更改 CSV 中列标题的一个元素