我正在运行包含postgres
即服务的Docker Compose应用程序。以下是docker-compose.yml
的一部分:
version: '3'
services:
postgres:
image: postgres
environment:
- POSTGRES_PASSWORD=foo
ports:
- 5432:5432
在docker-compose build
后跟docker-compose up
后,如果我docker ps
,我看到容器正在运行:
kurt@kurt-ThinkPad:~$ 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映射到localhost,我想我可以执行以下操作(在ipython
中):
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);")
所有这些命令执行时没有任何错误。为了检查结果,我尝试了(使用docker ps
中的容器ID):
kurt@kurt-ThinkPad:~$ docker exec -it 8a7a20686728 bash
root@8a7a20686728:/# 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
,而不是我尝试使用apks
创建的表psycopg2
。我没有正确创建表吗?
答案 0 :(得分:4)
听起来您可能没有启用自动提交,因此您对数据库所做的任何更改都不会被保存。尝试使用conn.autocommit = True
启用它,或者在执行命令conn.commit()
之后启用它。