2017-09-14 8 views
0

私はpsycopg2pythonを使用しています。Postgresql:psycopg2を使ってテーブルから別のカラムにコラムをコピーする方法は?

私は2つのテーブルを作成しました。 1つはdataと呼ばれ、データを入力したいと思っています。これを行うために、私はファイルからtemporarytableという一時テーブルを作成しました。

私は列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() 

が、私は問題があると思いSELECT * FROM temporarytable;

enter image description here

+0

ここで、 'temporarytable'を作成していますか?コピーしようとすると一時的なテーブルが既に削除されている可能性はありますか? –

+0

接続を閉じて再度開いて(一時表が削除される可能性があります)、通常の表を作成しないでください。 –

+0

@franciscosollimaそれは私が 'temporarytable'と呼ぶ正規のテーブルです – emax

答えて

0

た後、次のエラーにpgAdmin3からのスクリーンショットの下

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. 

を取得PostgreSQLのカラムはです。大文字と小文字を区別するです。あなたはSTAT2としてこれを試してみてください:あなたはまた、それらの上の文字を使用した列に対して"を使用する必要があります

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

注意を。

関連する問題