2017-05-31 6 views
2

私はサービスとしてpostgresを含むDocker Composeアプリケーションを実行しています。ここdocker-compose.ymlの一部は次のとおりです。pyscopg2を使ってPostgreSQLでテーブルを作成するには?

docker-compose up続い docker-compose build
version: '3' 

services: 
    postgres: 
    image: postgres 
    environment: 
     - POSTGRES_PASSWORD=foo 
    ports: 
     - 5432:5432 

私はdocker psをすれば、コンテナが実行されている参照してください。

[email protected]:~$ docker ps 
CONTAINER ID  IMAGE    COMMAND     CREATED    STATUS    PORTS     NAMES 
8a7a20686728  postgres   "docker-entrypoint..." 28 minutes ago  Up 17 seconds  0.0.0.0:5432->5432/tcp apkapi_postgres_1 

ポート5432をローカルホストにマッピングされているので、私は私ができる考え出し

In [1]: import psycopg2 

In [2]: conn = psycopg2.connect(dbname="postgres", user="postgres", password="fo 
    ...: o", host="localhost") 

In [3]: cursor = conn.cursor() 

In [4]: cursor.execute("CREATE TABLE apks (s3_uri text);") 

これらのコマンドはすべてエラーなしで実行されます(ipython)。結果を確認するには、私は(docker psからのコンテナIDを使用して)みました:

[email protected]:~$ docker exec -it 8a7a20686728 bash 
[email protected]:/# psql -U postgres 
psql (9.6.3) 
Type "help" for help. 

postgres=# \l 
           List of databases 
    Name | Owner | Encoding | Collate | Ctype | Access privileges 
-----------+----------+----------+------------+------------+----------------------- 
postgres | postgres | UTF8  | en_US.utf8 | en_US.utf8 | 
template0 | postgres | UTF8  | en_US.utf8 | en_US.utf8 | =c/postgres   + 
      |   |   |   |   | postgres=CTc/postgres 
template1 | postgres | UTF8  | en_US.utf8 | en_US.utf8 | =c/postgres   + 
      |   |   |   |   | postgres=CTc/postgres 
(3 rows) 

postgres=# \c postgres 
You are now connected to database "postgres" as user "postgres". 
postgres=# \dt 
      List of relations 
Schema | Name | Type | Owner 
--------+---------+-------+---------- 
public | mytable | table | postgres 
(1 row) 

問題は、私は、私が以前に作成したテーブルmytableを参照してくださいということですが、私はpsycopg2を使用して作成するために試したことのないテーブルapks 。テーブルを正しく作成していませんか?

+1

このシナリオでは重要なのですが、カーソルと接続を閉じるのはわかりませんか? –

答えて

3

自動コミットが有効になっていない可能性があるので、データベースに対する変更が保存されていないようです。 conn.autocommit = Trueを使用して有効にするか、実行コマンドの後にconn.commit()を使用して有効にしてください。

関連する問題