Postgresql:如何使用psycopg2将列从表复制到另一个表?

时间:2017-09-14 13:47:07

标签: python postgresql

我在psycopg2中使用python来管理我的数据库。

我创建了两个表。一个名为data的人,我希望填充一些数据。为此,我从temporarytable文件创建了一个名为.csv的临时表。

我想复制专栏numberofinhabitants。所以我正在做的是以下内容:

### Add Column
import psycopg2 as ps    
stat1 = """  ALTER TABLE data ADD COLUMN numberofinhabitants integer"""
con = ps.connect(dbname = 'mydb', user='postgres', host='localhost', password='mypd')
con.autocommit = True
cur = con.cursor()
cur.execute(stat1)
cur.close()
con.close()


### Copy Column
stat2 = """INSERT INTO data (numberofinhabitants) SELECT numberofinhabitants FROM temporarytable"""
con = ps.connect(dbname = 'mydb', user='postgres', host='localhost', password='mypd')
con.autocommit = True
cur = con.cursor()
cur.execute(stat2)
cur.close()
con.close()

但是我收到以下错误

ProgrammingError: column "numberofinhabitants" does not exist
LINE 1: INSERT INTO data (numberofinhabitants) SELECT numberofinhabi...
                                                      ^
HINT:  There is a column named "numberofinhabitants" in table "data", but it cannot be referenced from this part of the query.

pgAdmin3

之后的SELECT * FROM temporarytable;屏幕截图下方

enter image description here

1 个答案:

答案 0 :(得分:0)

我认为问题在于PostgreSQL的列是区分大小写。你应该试试这个stat2:

stat2 = """INSERT INTO data (numberofinhabitants) SELECT "numberOfInhabitants" FROM temporarytable"""

请注意,对于包含大写字符的列,您还应该使用"