我正在尝试在 MacOS 上实现配置此 project 的 postgres 数据库,因此我安装了 postgres、docker 并尝试在此 docker 文件上运行 class TextInput extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) { this.setState({value: event.target.value}); }
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} /> </label>
<input type="submit" value="Submit" />
</form>
);
}
}
:
docker-compose up -d
这里我的环境文件只有这一行:
version: "3"
services:
maadb-ps-db:
image: postgres:latest
container_name: maadb-ps-db
ports:
- "5433:5432"
env_file:
- postgres.env
volumes:
- database-data:/usr/local/var/postgres
volumes:
database-data:
然后,我尝试通过python和以下方法连接到数据库:
POSTGRES_HOST_AUTH_METHOD=trust
参数如下:
def get_resources_sql():
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
# TODO
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print("Database ERROR: ", error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
当我尝试运行代码时,出现以下错误:
[postgresql]
host=localhost
port=5433
database=maadbsql
如果我尝试通过 args {'host': 'localhost', 'port': '5433', 'database': 'maadbsql'}
Connecting to the PostgreSQL database...
Database ERROR: FATAL: role "username" does not exist
打开 maadbsql 数据库并检查权限,这就是我得到的(我只有两个用户,“用户名”和“postgres”):
我错过了什么吗?
编辑:
这是运行psql maadbsql
后的日志:link
这是关机后的日志:link
答案 0 :(得分:1)
我认为您没有适当地创建数据库。我将首先删除您的容器和卷:
docker-compose down -v
配置您的环境文件,以便 postgres 映像将为您的应用程序创建数据库和用户:
POSTGRES_HOST_AUTH_METHOD=trust
POSTGRES_USER=maadbsql
POSTGRES_DB=maadbsql
通过此更改,我可以成功运行以下 Python 代码:
>>> import psycopg2
>>> conn = psycopg2.connect('dbname=maadbsql user=maadbsql host=localhost port=5433')
>>> cur = conn.cursor()
>>> cur.execute('create table example(id int, name text)')
>>> conn.commit()
>>> cur.execute('insert into example (id, name) values (%s, %s)', (1, 'alice'))
>>> conn.commit()
>>> cur.execute('select * from example')
>>> cur.fetchall()
[(1, 'alice')]